<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/6/24
 * Time: 13:57
 */

namespace app\common\cachemodel;

use app\common\cachemodel\live\LiveAnswerAstroRecord;
use app\common\cachemodel\name_analyze\Zl9NameAnalyzeCreateNameRecord;
use app\common\cachemodel\name_analyze\Zl9NameAnalyzeRecord;
use app\common\cachemodel\zl1_relation\Zl1RelationAnalysisFitYou;
use app\common\cachemodel\zl1_relation\Zl1RelationAnalysisIdea;
use app\common\cachemodel\zl1_relation\Zl1RelationAnalysisReport;
use app\common\cachemodel\zl3\Zl3FortuneYearAnalysis;
use app\common\cachemodel\zl4\Zl4GoodTimeTag;
use app\common\cachemodel\zl4\Zl4HoroscopeGoodTime;
use app\common\cachemodel\zl4\Zl4HoroscopeGoodTimeTemp;
use app\common\cachemodel\zl4\Zl4HoroscopeReport;
use app\common\cachemodel\zl6\Zl6Meditation;
use app\common\cachemodel\zlcr2\Zlcr2UserQuestion;
use app\common\lib\exception\ApiException;
use app\common\lib\MentalTestUtil;
use app\common\lib\Orders as OrdersLib;
use app\common\lib\Util;
use app\common\model\BaseCache;
use app\common\pay\Ali;
use app\common\pay\Weixin;
use Exception;
use think\Cache;
use think\Db;
use think\Env;
use think\Log;
use think\response\Json;
use XznsTools\cache\CacheManage;

/**
 * 订单模型
 * Class Orders
 * @package app\common\model
 */
class Orders extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.app_orders';

    protected $update = ['update_time'];

    protected $cacheModel = 'orders.orders';

    /**
     * 设置器,updatetime默认存入时间戳
     * @return int
     */
    public function setUpdateTimeAttr()
    {
        return time();
    }

    /**
     * 获取用户总消费金额
     * @param $uid
     * @return float|int|mixed|string
     */
    public function getUserTotalAmount($uid)
    {
        $total = Cache::get('user_total_amount_' . $uid);
        if ($total === false)
        {
            try
            {
                $total = $this->where(['uid' => $uid, 'status' => [1, 4]])->sum('total_amount');
            }
            catch (\Exception $e)
            {
                $total = 0;
            }
            Cache::set('user_total_amount_' . $uid, $total, 86400);
        }
        return $total;
    }

    /**
     * 批量获取订单信息
     * @param       $ids
     * @param array $filed
     * @return array|false
     * @throws Exception
     */
    public function batchGetInfo($ids, array $filed = [])
    {
        $data = CacheManage::getInstance()->setCacheConfig('orders.orders')
            ->batchGetCache($ids, function ($ids)
            {
                $where = ['order_id' => ['in', $ids]];
                try
                {
                    $data = $this->where($where)->order('id', 'DESC')->column('id,is_del,status,order_type,uid,gid,order_id,fid,reid,trade_type,total_amount,create_time,transaction_id,pay_time,return_time,account,extend,env_type', 'order_id');
                }
                catch (Exception $e)
                {
                    $data = [];
                }

                return $data;
            }, $filed, 'list_details');

        return $data;
    }

    /**
     * 获取订单信息和档案rids和商品gids
     * @param $order_id
     * @return mixed
     * @throws Exception
     */
    public function OrderRidsInfo($order_id)
    {
        $orders = current($this->batchGetInfo([$order_id]));
        $orders['order_type'] = (int)($orders['order_type'] ?? 0);
        $orders['rids'] = [];
        $orders['gids'] = [];
        switch (true)
        {
            case $orders['order_type'] === 1: //获取校准生辰的档案
                $recs = (new Rectification())->getRecDetail([$orders['reid']]);
                $orders['rids'][] = current($recs)['rid'] ?: 0;
                $orders['gids'][] = $orders['gid'];
                break;
            case in_array($orders['order_type'], [2, 3, 4, 12], false)://获取运势的档案
                $fortunes = current((new Fortune())->batchGetInfo([$orders['fid']], ['id', 'type', 'time', 'rids', 'extend']));
                $orders['rids'] = $fortunes['rids'] ? explode(',', $fortunes['rids']) : [];
                $orders['gids'][] = $orders['gid'];
                break;
            case in_array($orders['order_type'], [5, 7, 13], false)://获取幸运之城详情和本命预测的档案
                $order_middle = current((new OrdersGoods())->batchGetInfo([$orders['id']])) ?: [];
                foreach ($order_middle as $order_good)
                {
                    $og = json_decode($order_good, true);
                    $orders['rids'][] = $og['rid'];
                    $orders['gids'][] = $og['gid'];
                }
                break;
        }
        return $orders;
    }

    /**
     * 更新订单缓存
     * @param $order_id /更新的id
     * @param $status /更新的状态  0=>未支付  1=>等待计算|等待矫正|等待发货  2=>交易关闭  3=>退款成功  4=>计算成功|矫正成功|已支付  5=>等待收货
     * @throws Exception
     */
    public function UpdateCache($order_id, $status = -1)
    {
        //获取订单rids，type，status
        $cacheInit = CacheManage::getInstance();
        $OrderInfo = $this->OrderRidsInfo($order_id);
        if (!isset($OrderInfo['status']))
        {
            Log::write('更新订单缓存数据异常,订单数据为:' . json_encode($OrderInfo, JSON_UNESCAPED_UNICODE), 'error', true);
        }
        if ($OrderInfo['status'] == 0)
        {
            $this->cacheModel = 'orders.orders_unpaid';
            switch (true)
            {
                case  in_array($OrderInfo['order_type'], [6, 8], false):
                    //更新订单详情缓存
                    $cacheInit->setCacheConfig($this->cacheModel, $OrderInfo['uid'])->setListKeyType($OrderInfo['order_type'])->rmCache('list');
                    //                    $this->listDataDel($OrderInfo['uid'], [$order_id], $OrderInfo['order_type']);
                    break;
                case in_array($OrderInfo['order_type'], [1, 2, 3, 4, 5, 7, 12, 13], false):
                    foreach ($OrderInfo['rids'] as $rid)
                    {
                        $cacheInit->setCacheConfig($this->cacheModel, $rid)->setListKeyType($OrderInfo['order_type'])->rmCache('list');
                    }
                    break;
            }
        }
        if ($status == 1 || $status == 4)
        {
            $this->cacheModel = 'orders.orders_prepaid';
            switch (true)
            {
                case  in_array($OrderInfo['order_type'], [6, 8], false):
                    $this->listDataAdd($OrderInfo['uid'], [$order_id => $order_id], $OrderInfo['order_type']);
                    break;
                case (in_array($OrderInfo['order_type'], [1, 2, 3, 4, 5, 7, 12, 13], false)):
                    foreach ($OrderInfo['rids'] as $rid)
                    {
                        if ($OrderInfo['order_type'] == 5)
                        {
                            // 删除幸运之城赠送缓存
                            Cache::rm('recode_lines_' . $rid);
                        }
                        //                        CacheManage::getInstance()->setCacheConfig($this->cacheModel, $rid)->setListKeyType($OrderInfo['order_type'])->rmCache('list');
                        $this->listDataAdd($rid, [$order_id => $order_id], $OrderInfo['order_type']);
                    }
                    break;
            }
        }
        //更新订单详情缓存
        $cacheInit->setCacheConfig('orders.orders', $order_id)->rmCache();
    }

    /**
     * 删除订单缓存,is_del变动
     * @param $order_id
     * @return bool
     * @throws Exception
     */
    public function DelCache($order_id)
    {
        //获取订单rids，type，status
        $OrderInfo = $this->OrderRidsInfo($order_id);
        $cacheInit = CacheManage::getInstance();
        $this->cacheModel = 'orders.orders';
        $cacheInit->setCacheConfig($this->cacheModel, $order_id)->rmCache();
        if ($OrderInfo['order_status'] == 0)
        {
            $this->cacheModel = 'orders.orders_unpaid';
            switch (true)
            {
                case $OrderInfo['type'] == 6:
                    //更新订单详情缓存
                    $cacheInit->setCacheConfig($this->cacheModel, $OrderInfo['uid'])->setListKeyType($OrderInfo['order_type'])->rmCache('list');
                    //                    $this->listDataDel($OrderInfo['uid'], [$order_id], $OrderInfo['order_type']);
                    break;
                case in_array($OrderInfo['type'], [1, 2, 3, 4, 5, 7], false):
                    foreach ($OrderInfo['rids'] as $rid)
                    {
                        $cacheInit->setCacheConfig($this->cacheModel, $rid)->setListKeyType($OrderInfo['order_type'])->rmCache('list');
                        //                        $this->listDataDel($rid, [$order_id], $OrderInfo['order_type']);
                    }
                    break;
            }
        }
        return true;
    }

    /**
     * 新增订单
     * @param       $uid
     * @param       $type 1=>校准生辰,2=>日运,3=>月运,4=>年运,5=>幸运之城,6=>教学视频,7=>本命预测
     * @param       $map
     * @param array $rids
     * @return int|string
     */
    public function SaveData($map)
    {
        try
        {
            $map['channel'] = Util::getChannelId();
            $oid = $this->insertGetId($map);
        }
        catch (Exception $e)
        {
            Log::write('订单入库失败：' . $e->getMessage() . '【' . $e->getFile() . $e->getLine() . '】', 'error', true);
            return false;
        }
        return $oid;
    }

    /**
     * 订单退款
     * @param     $uid
     * @param     $orders
     * @param     $refund_amount
     * @param int $liveRecordId
     * @return array
     * @throws \think\exception\PDOException
     */
    public function refund($uid, $orders, $refund_amount, $liveRecordId = 0)
    {
        if (isset($orders['status']) && (int)$orders['status'] === 3)
        {
            return [
                'status' => true,
                'msg' => '退款成功',
            ];
        }
        $this->startTrans();
        try
        {
            $account = \app\common\cachemodel\OrdersLib::getOrderAccountType($orders['order_id'], $orders['trade_type']);
            $out_request_no = date('Ymd') . $orders['id'] . substr(md5(time()), 0, 2);
            switch ($orders['trade_type'])
            {
                case 1:
                    $response = \GuzzleHttp\json_decode(\GuzzleHttp\json_encode((new Ali())->refund(['out_trade_no' => $orders['order_id'], 'refund_amount' => $refund_amount, 'out_request_no' => $out_request_no], $account['account'])), true);
                    // 支付宝已经内置验签 支付成功
                    if ($response['alipay_trade_refund_response']['code'] !== '10000')
                    {
                        return [
                            'status' => false,
                            'msg' => $response['alipay_trade_refund_response']['sub_msg'] ?? '退款失败',
                        ];
                    }
                    break;
                case 2:
                    $weixin = new Weixin();
                    $accountConfig = \app\common\cachemodel\OrdersLib::getOrderAccountType($orders['order_id'], 2);
                    $wxpayConfig = OrdersLib::getPayConfig('wx', $accountConfig['account']);
                    $wxPayType = $wxpayConfig['wx_pay_type'][$orders['trade_type']];
                    // 获取微信配置信息
                    $wxConfig = $wxpayConfig[$wxPayType['configName']];
                    $wxConfig['out_refund_no'] = $out_request_no;
                    $wxConfig['total_fee'] = sprintf('%u', bcmul($orders['total_amount'], 100));// 以分为单位的
                    $wxConfig['refund_fee'] = sprintf('%u', bcmul($refund_amount, 100));// 以分为单位的
                    $res = $weixin->refund($orders['order_id'], $wxConfig);
                    if ($res['return_code'] === 'SUCCESS')
                    {
                        if ($res['result_code'] === 'FAIL')
                        {
                            return [
                                'status' => false,
                                'msg' => $res['err_code_des'] ?? '退款失败',
                            ];
                        }

                    } else
                    {
                        return [
                            'status' => false,
                            'msg' => $res['return_msg'] ?? '退款失败',
                        ];
                    }
                    break;
                case 4:
                    (new ZhunleUserAccount())->refund($uid, $orders, $refund_amount, 4, '', $liveRecordId);
                    break;
            }
            //添加退款数据
            $refundData = [
                'uid' => $uid,
                'order_id' => $orders['order_id'],
                'refund_price' => $refund_amount,
                'order_type' => $orders['order_type'],
                'out_refund_no' => $out_request_no,
                'trade_type' => $orders['trade_type'],
                'create_time' => time(),
            ];
            (new AppOrdersRefund())->saveData($refundData);
            $this->commit();
        }
        catch (\Exception $e)
        {
            Log::write('订单退款失败：' . $e->getMessage() . '订单编号：' . $orders['order_id'] . '失败文件信息：【' . $e->getFile() . '：' . $e->getLine() . '】', 'error', true);
            $this->rollback();
            return [
                'status' => false,
                'msg' => '退款失败',
            ];
        }
        $this->UpdateData($orders['order_id'], ['status' => 3, 'return_time' => time()], 3);
        return [
            'status' => true,
            'msg' => '退款成功',
        ];
    }

    /**
     * 更新订单
     * @param     $order_id
     * @param     $map
     * @param int $status 更新的状态 0=>未支付  1=>已支付/等待计算|等待矫正   2=>交易关闭   3=>退款成功 4=>计算成功|矫正成功  5=>队列失败
     * @return bool
     */
    public function UpdateData($order_id, $map, $status = -1)
    {
        try
        {
            $nowTime = time();
            $map['update_time'] = $nowTime;
            $this->where(['order_id' => $order_id])->update($map);
            $this->UpdateCache($order_id, $status);
        }
        catch (\Exception $e)
        {
            $uri = Util::requestAddress();
            Log::write('Orders model => ()更新数据异常：' . $e->getMessage() . "订单编号:" . $order_id . "失败信息：" . $e->getFile() . ':' . $e->getLine() . "请求路径：" . $uri, 'error', true);
            return false;
        }
        return true;
    }

    /**
     * 修改订单status
     * @param $order_id
     * @param $map
     * @return bool
     */
    public function DelData($order_id, $map)
    {
        try
        {
            $this->where(['order_id' => $order_id])->update($map);
            $this->DelCache($order_id);
        }
        catch (Exception $e)
        {
            return false;
        }
        return true;
    }

    /**
     * 获取用户所有订单信息
     * @param int $uid
     * @param int $type [0=>全部,1=>待支付,2=>进行中,3=>已完成，4=》已取消]
     * @param string $order_type 1=>校准生辰 2=>日运 3=>月运 4=>年运 5=>幸运之城 6=>教学视频 7=>本命预测 8=>vip会员 9=>准币 14=>商城 15=>定制报告
     * @param string $filter 过滤的类型 1=>校准生辰 2=>日运 3=>月运 4=>年运 5=>幸运之城 6=>教学视频 7=>本命预测 8=>vip会员
     * @param bool $haveIds true=>返回ids，false=>不返回ids
     * @param bool $is_live 直播间订单筛选
     * @return array
     * @throws Exception
     */
    public function getUserAllOrder($uid, $type, $order_type = '', $filter = '', $haveIds = false, $is_live = false)
    {
        $defaultFilter = '12,13';//默认过滤小程序订单类型
        if ($filter)
        {
            $filter .= ',' . $defaultFilter;
        } else
        {
            $filter = $defaultFilter;
        }
        $page = input('page', 1);
        $orderTypeArr = explode(',', $order_type);
        //查询心理测试订单同时查询后天星座订单
        if (in_array(18, $orderTypeArr, false))
        {
            $orderTypeArr = array_merge([32], $orderTypeArr);
        }
        //查询AI骰子订单同时查询AI问答订单
        if (in_array(30, $orderTypeArr, false))
        {
            $orderTypeArr = array_merge($orderTypeArr, [31, 34]);
        }
        $order_type = implode(',', $orderTypeArr);
        //  订单状态  0=>未支付  1=>等待计算|等待矫正   2=>交易关闭   3=>退款成功  4=>计算成功|矫正成功|已支付
        $this->cacheModel = 'orders.orders';
        switch (true)
        {
            case $order_type://新版本根据订单类型进行查询
                $where = "uid = $uid and is_del = 0 and order_type in ($order_type) and ";
                break;
            case $filter://老版本过滤
                $where = "uid = $uid and is_del = 0 and order_type not in ($filter) and ";
                break;
            default:
                $where = "uid = $uid and is_del = 0 and ";
                break;
        }

        switch ($type)
        {
            //待支付
            case 1:
                $where .= 'status = 0 and ';
                break;
            //进行中
            case 2:
                $where .= 'status in (1,5) and ';
                break;
            //已完成
            case 3:
                $where .= 'status in (3,4) and ';
                break;
            //已取消,已关闭
            case 4:
                $where .= 'status = 2 and ';
                break;
        }
        if ($is_live)
        {
            $where .= "env_type=8";//筛选直播间订单
        } else
        {
            $where .= "(env_type=1 or (env_type >1 and status > 0) or env_type=8)";//过滤等待支付的非app下单的订单
        }
        try
        {
            $data = $this->field('order_id')->where($where)->order('id', 'DESC')->paginate(10, false, ['query' => $page])->toArray();
            $ids = $data ? array_column($data['data'], 'order_id') : [];
        }
        catch (Exception $e)
        {
            $data = [
                'total' => 0,
                'per_page' => $page,
                'current_page' => 1,
                'last_page' => 1,
                'data' => [],
            ];
            $ids = [];
        }

        $data['data'] = $this->batchGetInfo($ids, ['id', 'is_del', 'status', 'order_type', 'uid', 'gid', 'order_id', 'fid', 'reid', 'trade_type', 'total_amount', 'create_time', 'transaction_id', 'pay_time', 'return_time', 'account', 'extend', 'env_type']);
        if ($haveIds)
        {
            $data['ids'] = $ids;
        }
        return $data;
    }

    /**
     * 获取当前档案/用户未支付或已支付的订单编号
     * @param $uid
     * @param $rid
     * @param $order_type 1=>校准生辰 2=>日运 3=>月运 4=>年运 5=>幸运之城 6=>教学视频 7=>发现自我 8=>vip会员 9=>准币（在user_account表中），10=>祈福，12=>精简版月运，13=>精简版报告，14=>商城,15=>定制报告，16=>塔罗,17=>合盘报告,18=>心理测试
     * @param $order_status
     * @return array|false|mixed
     * @throws Exception
     */
    public function PrepaidUnpaidOrderIds($uid, $rid, $order_type, $order_status)
    {
        switch ($order_status)
        {
            case 0:
                $this->cacheModel = 'orders.orders_unpaid';
                break;
            case 1:
                $this->cacheModel = 'orders.orders_prepaid';
                break;
            default:
                return false;
                break;
        }

        //获取缓存key
        if (in_array($order_type, [6, 8], false))
        {
            $id = $uid;
        } else
        {
            $id = $rid;
        }

        return CacheManage::getInstance()->setCacheConfig($this->cacheModel, $id)
            ->setListKeyType($order_type)
            ->ZsGetIocData('list', function () use ($uid, $rid, $order_type, $order_status)
            {
                switch ($order_status)
                {
                    //获取未支付订单
                    case 0:
                        return $this->getUserUnpaidOrderIdFromData($uid, $rid, $order_type);
                    //获取已支付订单
                    case 1:
                        return $this->getUserPrepaidOrderIdFromData($uid, $rid, $order_type);
                    default :
                        return false;
                }
            });
    }

    /**
     * 获取当前档案/用户未支付或已支付的订单
     * @param $rid
     * @param $order_type 1=>校准生辰 2=>日运 3=>月运 4=>年运 5=>幸运之城 6=>教学视频 7=>发现自我 8=>vip会员 9=>准币（在user_account表中），10=>祈福，12=>精简版月运，13=>精简版报告，14=>商城,15=>定制报告，16=>塔罗,17=>合盘报告,18=>心理测试
     * @param $uid
     * @param $order_status 0=>未支付,1=>已支付
     * @return array | bool
     * @throws Exception
     */
    public function PrepaidUnpaidOrder($uid, $rid, $order_type, $order_status)
    {
        $oids = $this->PrepaidUnpaidOrderIds($uid, $rid, $order_type, $order_status);
        $orders = $this->batchGetInfoByIds($oids);
        return (new OrdersLib())->getOrderDetails($orders);
    }

    /**
     * 从数据库获取用户已支付的订单id
     * @param int $uid
     * @param     $rid
     * @param     $type 1=>校准生辰 2=>日运 3=>月运 4=>年运 5=>幸运之城 6=>教学视频 7=>发现自我 8=>vip会员 9=>准币（在user_account表中），10=>祈福，12=>精简版月运，13=>精简版报告，14=>商城,15=>定制报告，16=>塔罗,17=>合盘报告,18=>心理测试
     * @return array
     * @throws Exception
     */
    public function getUserPrepaidOrderIdFromData($uid, $rid, $type)
    {
        $type = (int)$type;
        switch (true)
        {
            case $type === 1://生时矫正
                try
                {
                    // $data = $this
                    //     ->alias('o')
                    //     ->join('wechat_backup_07_18_14_43_00.app_rectification re', 'o.reid=re.id')
                    //     ->where(['o.status' => ['in', [1, 4]], 'o.order_type' => $type, 'o.uid' => $uid, 're.rid' => $rid])
                    //     ->order('o.id', 'DESC')
                    //     ->column('o.order_id', 'o.order_id');
                    $data = Db::table('wechat_backup_07_18_14_43_00.app_rectification')->alias('re')->join('wechat_backup_07_18_14_43_00.app_orders o', 're.id=o.reid')
                        ->where(['o.status' => ['in', [1, 4]], 'o.order_type' => $type, 'o.uid' => $uid, 're.rid' => $rid])
                        ->order('re.id', 'DESC')
                        ->column('o.order_id');
                }
                catch (Exception $e)
                {
                    Log::write('获取生时矫正已支付订单信息失败：' . $e->getMessage() . PHP_EOL . '失败文件信息:【' . $e->getFile() . $e->getLine() . '】', 'error', true);
                    $data = [];
                }
                break;
            case in_array($type, [2, 3, 4, 12], true)://多档案
                try
                {
                    // $data = $this
                    //     ->alias('o')
                    //     ->join('wechat_backup_07_18_14_43_00.app_fortune f', 'o.fid=f.id')
                    //     ->where("o.status in (1,4) AND o.order_type={$type} AND o.uid={$uid} AND find_in_set($rid,f.rids)")
                    //     ->order('o.id', 'DESC')
                    //     ->column('o.order_id', 'o.order_id');
                    $data = Db::table('wechat_backup_07_18_14_43_00.app_fortune')->alias('f')->join('wechat_backup_07_18_14_43_00.app_orders o', 'o.fid=f.id')
                        ->where("o.status in (1,4) AND o.order_type={$type} AND o.uid={$uid} AND find_in_set($rid,f.rids)")
                        ->order('o.id DESC')
                        ->column('o.order_id');
                }
                catch (Exception $e)
                {
                    Log::write('获取运势已支付订单信息失败：' . $e->getMessage() . PHP_EOL . '失败文件信息:【' . $e->getFile() . $e->getLine() . '】', 'error', true);
                    $data = [];
                }
                break;
            case  in_array($type, [5, 7, 13], true)://多商品
                try
                {
                    // $data = $this
                    //     ->alias('o')
                    //     ->join('wechat_backup_07_18_14_43_00.app_orders_goods og', 'o.id=og.oid')
                    //     ->where(['o.status' => ['in', [1, 4]], 'o.order_type' => $type, 'o.uid' => $uid, 'og.rid' => $rid])
                    //     ->order('o.id', 'DESC')
                    //     ->column('o.order_id', 'o.order_id');
                    $data = Db::table('wechat_backup_07_18_14_43_00.app_orders_goods')->alias('og')->join('wechat_backup_07_18_14_43_00.app_orders o', 'o.id=og.oid')
                        ->where(['o.status' => ['in', [1, 4]], 'o.order_type' => $type, 'o.uid' => $uid, 'og.rid' => $rid])
                        ->order('o.id DESC')
                        ->column('o.order_id');
                }
                catch (Exception $e)
                {
                    Log::write('获取多商品已支付订单信息失败：' . $e->getMessage() . PHP_EOL . '失败文件信息:【' . $e->getFile() . $e->getLine() . '】', 'error', true);
                    $data = [];
                }
                break;
            case $type === 6:
                try
                {
                    $data = $this
                        ->alias('o')
                        ->where(['o.status' => ['in', [1, 4]], 'o.order_type' => $type, 'o.uid' => $uid])
                        ->order('o.id', 'DESC')
                        ->column('o.order_id', 'o.order_id');
                }
                catch (Exception $e)
                {
                    Log::write('获取视频已支付订单信息失败：' . $e->getMessage() . PHP_EOL . '失败文件信息:【' . $e->getFile() . $e->getLine() . '】', 'error', true);
                    $data = [];
                }
                break;
            default:
                return [];
        }
        $data = array_flip_key_value($data);
        return $data;
    }

    /**
     * 从数据库获取用户未支付的订单id
     * @param int $uid
     * @param     $rid
     * @param     $type 1=>校准生辰,2=>日运,3=>月运,4=>年运,5=>幸运之城,6=>教学视频,7=>本命预测
     * @return array
     */
    public function getUserUnpaidOrderIdFromData($uid, $rid, $type)
    {
        $where = ['o.status' => 0, 'o.order_type' => $type, 'o.is_del' => 0, 'o.uid' => $uid];
        switch (true)
        {
            case $type == 1://生时矫正
                try
                {
                    $data = $this
                        ->alias('o')
                        ->join('wechat_backup_07_18_14_43_00.app_rectification re', 'o.reid=re.id')
                        ->where(['re.rid' => $rid])
                        ->where($where)
                        ->order('o.id', 'DESC')
                        ->column('o.order_id', 'o.order_id');
                }
                catch (Exception $e)
                {
                    $data = [];
                }
                break;
            case in_array($type, [2, 3, 4, 12])://多档案
                $where1 = "find_in_set($rid,f.rids)";
                try
                {
                    $data = $this
                        ->alias('o')
                        ->join('wechat_backup_07_18_14_43_00.app_fortune f', 'o.fid=f.id')
                        ->where($where)
                        ->where($where1)
                        ->order('o.id', 'DESC')
                        ->column('o.order_id', 'o.order_id');
                }
                catch (Exception $e)
                {
                    $data = [];
                }
                break;
            case  in_array($type, [5, 7, 13])://多商品
                try
                {
                    $data = $this
                        ->alias('o')
                        ->join('wechat_backup_07_18_14_43_00.app_orders_goods og', 'o.id=og.oid')
                        ->where($where)
                        ->where(['og.rid' => $rid])
                        ->order('o.id', 'DESC')
                        ->column('o.order_id', 'o.order_id');
                }
                catch (Exception $e)
                {
                    $data = [];
                }
                break;
            case  in_array($type, [6, 8]):
                try
                {
                    $data = $this
                        ->alias('o')
                        ->where($where)
                        ->order('o.id', 'DESC')
                        ->column('o.order_id', 'o.order_id');
                }
                catch (Exception $e)
                {
                    $data = [];
                }
                break;
            default:
                return [];
        }
        $data = array_flip_key_value($data);
        return $data;
    }

    /**
     * 缓存商品的已经购买数
     * @param      $type 1=>校准生辰,2=>日运,3=>月运,4=>年运,5=>幸运之城,6=>教学视频,7=>本命预测  8=>会员 ，9=>准币，12=>月运精简版，13=>本命报告精简版，15=>定制报告
     * @param int $gid 教学视频 本命报告 时传
     * @param null $relationId 合盘报告关系ID
     * @return array|bool|mixed
     * @throws \think\Exception
     */
    public function getTotalPrepaidOrder($type, $gid = 0, $relationId = null)
    {
        $this->cacheModel = 'orders.orders_prepaid_num';
        $cackeKey = is_null($relationId) ? $type . '-' . $gid : $type . '-' . $gid . '-' . $relationId;

        $num = CacheManage::getInstance()->setCacheConfig($this->cacheModel, $cackeKey)->getDataAndSet(function () use ($type, $gid, $relationId)
        {
            $number = $this->getTotalPrepaidOrderFromDms($type, $gid, $relationId);
            return ['num' => $number];
        }, ['num']);
        return is_array($num) ? current($num) : (int)$num;
    }

    /**
     * 商品的已经购买数缓存自增 todo 合盘报告修改
     * @param int $type
     * @param int $gid
     * @param null $relationId 合盘报告关系ID
     * @return false|int|void
     * @throws \think\Exception
     */
    public function SaveTotalPrepaidOrder(int $type, $gid = 0, $relationId = null)
    {
        $this->cacheModel = 'orders.orders_prepaid_num';

        $cackeKey = is_null($relationId) ? $type . '-' . $gid : $type . '-' . $gid . '-' . $relationId;
        // 更新 订单数 缓存
        CacheManage::getInstance()->setCacheConfig($this->cacheModel, $cackeKey)->hashDataInc('num', 1, function () use ($type, $gid, $relationId)
        {
            return $this->getTotalPrepaidOrderFromDms($type, $gid, $relationId);
        });
    }

    /**
     * 数据库获取商品购买数
     * @param $type
     * @param $gid
     * @param $relationId
     * @return int|string
     * @throws \think\Exception
     */
    private function getTotalPrepaidOrderFromDms(int $type, $gid, $relationId = null)
    {
        $where = ['o.order_type' => $type, 'o.status' => ['in', [1, 4]]];
        switch (true)
        {
            case in_array($type, [1, 2, 3, 4, 6, 12], true):
                $number = $this
                    ->alias('o')
                    ->where($where)
                    ->where(['o.gid' => $gid])
                    ->distinct(true)
                    ->count('o.id');
                break;
            case in_array($type, [5, 7, 13], true)://多商品订单
                $number = $this
                    ->alias('o')
                    ->join('wechat_backup_07_18_14_43_00.app_orders_goods og', 'o.id=og.oid', 'LEFT')
                    ->where($where)
                    ->where(['og.gid' => $gid])
                    ->distinct(true)
                    ->count('o.id');
                break;
            case $type === 17:
                $where = is_null($relationId) ? ['srid' => $gid] : ['srid' => $gid, 'relation_id' => $relationId];
                $number = Db::table('wechat_backup_07_18_14_43_00.zl_synastry_report')->where($where)->count(); // 考虑到软删除 直接使用DB 不使用模型了
                break;
            case $type === 15://定制报告
                $number = $this
                    ->alias('o')
                    ->where($where)
                    ->distinct(true)
                    ->count('o.id');
                break;
            default :
                $number = 0;
                break;
        }
        return $number;
    }

    /**
     * 从数据库批量获取订单信息,根据订单id
     * @param $ids
     * @param $type
     * @param $sortType
     * @return array|null
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        $where = ['order_id' => ['in', $ids]];

        try
        {
            $data = $this->where($where)->order('id', 'DESC')->column('id,is_del,status,order_type,uid,gid,order_id,fid,reid,trade_type,total_amount,create_time,transaction_id,pay_time,return_time,account,extend,env_type', 'order_id');
        }
        catch (Exception $e)
        {
            $data = [];
        }

        return $data;
    }


    /**
     * 获取订单状态描述
     * @param $order
     * @throws Exception
     */
    public function statusDesInfo(&$order)
    {
        $order['is_display_recommend_data'] = 0;//是否显示推荐信息，0=>不显示，1=》显示
        $order['time_remaining'] = 0;//订单剩余支付时间
        //订单关闭，等待支付，等待计算（校准生辰）不可跳转
        $btns = config('zhunleorder');
        if (in_array($order['order_type'], [19, 20, 21], false))
        {
            $valid_time = $order['create_time'] + $btns['close_answer_time'];//5分钟未支付关闭订单
        } else
        {
            $valid_time = $order['create_time'] + $btns['close_order_time'];//30分钟未支付关闭订单
        }
        //订单剩余关闭时间
        $time_remaining = $valid_time - time();
        $time_remaining = $time_remaining > 0 ? $time_remaining : 0;
        //未支付订单，处理订单关闭状态
        if ($order['status'] == 0)
        {
            $order['status'] = $time_remaining ? $order['status'] : 2;
        }
        //订单按钮
        $order['order_icon'] = $this->orderStatusIcon($order['status']);
        switch ($order['status'])
        {
            case 0:
                $order['status_des'] = '等待支付';
                $order['des'] = '请在' . (int)($btns['close_order_time'] / 60) . '分钟内完成支付';
                $order['time_remaining'] = $time_remaining;
                $order['is_skip'] = 0;
                break;
            case 1:
                //若是有队列的商品，则增加订单描述
                if (in_array($order['order_type'], [1, 3, 4, 5, 7, 15, 17, 23, 25, 26, 27], false))
                {
                    $order['status_des'] = '预测进行中';
                    $order['des'] = '购买成功后，24小时内会给您预测结果';
                } elseif (in_array($order['order_type'], [19, 20, 21], false))
                {
                    $order['status_des'] = '等待解答中';
                    $order['des'] = '主播会在直播间为你解答';
                } elseif ($order['order_type'] == 14)
                {
                    $order['status_des'] = '待发货';
                } elseif ($order['order_type'] == 22)
                {
                    $order['status_des'] = '进行中';
                } elseif ($order['order_type'] == 24)
                {
                    $order['status_des'] = '正在筛选中';
                    $order['des'] = '购买成功后，24小时内会给您筛选结果';
                } elseif (in_array($order['order_type'], [28, 35]))
                {
                    $order['status_des'] = '预测进行中';
                    $order['des'] = '购买成功后，3小时内给您预测结果';
                } else
                {
                    $order['status_des'] = '订单完成';
                }
                if ($order['order_type'] == 1)
                {
                    $order['is_skip'] = 0;
                }
                break;
            case 2:
                $order['status_des'] = '订单关闭';
                $order['is_display_recommend_data'] = 1;
                $order['is_skip'] = 0;
                if ((int)$order['order_type'] === 18)
                {
                    $order['is_skip'] = 1;
                }
                $order['total_amount'] = '0.00';
                break;
            case 3:
                $order['status_des'] = '退款成功';
                $order['is_skip'] = 0;
                break;
            case 4:
                $order['status_des'] = '订单已完成';
                $order['is_display_recommend_data'] = 1;
                break;
            case 5:
                $order['status_des'] = '待收货';
                $kdTime = $mallInfo['kd_send_time'] ?? $order['pay_time'];
                $fifTime = strtotime('+15days', $kdTime);
                if (time() > $fifTime)
                {
                    $order['des'] = '订单已完成';
                    $order['status'] = 4;
                    $order['status_des'] = '订单已完成';
                    $this->UpdateData($order['order_id'], ['status' => 4], 4);
                } else
                {
                    $mallTime = (new Util())->timediff(time(), dateModify('U', $kdTime, '+15days'));
                    $order['des'] = $mallTime['day'] . '天' . $mallTime['hour'] . '小时' . $mallTime['min'] . '分钟后自动确认收货';
                }
                break;
        }
    }

    /**
     * 获取订单不同状态时的图标
     * @param $status
     * @return string
     */
    public function orderStatusIcon($status)
    {
        $link_prefix = Env::get('host.photo');
        if (Util::checkAppVersion('2.15.0') === '小')
        {
            $icon = [
                $link_prefix . 'test/order/unpaid.png',
                $link_prefix . 'test/order/computing.png',
                $link_prefix . 'test/order/cancel.png',
                $link_prefix . 'test/order/completed.png',
                $link_prefix . 'test/order/completed.png',
                $link_prefix . 'test/order/completed.png',
            ];
        } else
        {
            $icon = [
                $link_prefix . 'test/order/unpaid2.png',
                $link_prefix . 'test/order/computing2.png',
                $link_prefix . 'test/order/cancel2.png',
                $link_prefix . 'test/order/refund2.png',
                $link_prefix . 'test/order/completed2.png',
                $link_prefix . 'test/order/completed2.png',
            ];
        }
        return $icon[$status] ?? '';
    }

    /**
     * 获取订单跳转方式
     * @des 1=>校准生辰 2=>日运 3=>月运 4=>年运 5=>幸运之城 6=>教学视频 7=>本命预测 8=>vip会员 9=>准币（在user_account表中），10=>祈福，12=>精简版月运，13=>精简版报告，14=>商城，15=>定制报告
     * @param array $orders
     * @return mixed
     * @throws Exception
     */
    public function orderTypeLink($orders)
    {
        $isHistory = false;
        $host = Env::get('host.domain');
        if (Util::CheckAppVersion('2.6.0') !== '小')
        {
            if (in_array($orders['order_type'], [3, 4], false))
            {
                if ($orders['recode_info']['status'])
                {
                    if ($orders['order_type'] == 3)
                    {
                        $fortuneInfo = current((new MonthFortune())->batchGetRecodeFortuneMonthInfo((int)$orders['rid'], [$orders['time']]));
                        $fRecode = $orders['recode_info'];
                        // 档案唯一标示Key
                        $recodeUniqueKey = "{$fRecode['type']}:{$fRecode['year']}:{$fRecode['month']}:{$fRecode['day']}:{$fRecode['hour']}:{$fRecode['minute']}:{$fRecode['timezone']}:{$fRecode['ew']}:{$fRecode['long_deg']}:{$fRecode['long_min']}:{$fRecode['ns']}:{$fRecode['lat_deg']}:{$fRecode['lat_min']}:{$fRecode['is_summer']}";
                    } else
                    {
                        $fortuneInfo = current((new YearFortune())->batchGetRecodeFortuneYearInfo((int)$orders['rid'], [$orders['time']]));
                        $fRecode = $orders['recode_info'];
                        // 档案唯一标示Key
                        $recodeUniqueKey = "{$fRecode['type']}:{$fRecode['year']}:{$fRecode['month']}:{$fRecode['day']}:{$fRecode['hour']}:{$fRecode['minute']}:{$fRecode['timezone']}:{$fRecode['ew']}:{$fRecode['long_deg']}:{$fRecode['long_min']}:{$fRecode['ns']}:{$fRecode['lat_deg']}:{$fRecode['lat_min']}:{$fRecode['is_summer']}:{$fRecode['live_country']}{$fRecode['live_province']}{$fRecode['live_city']}";
                    }
                    if (count($fortuneInfo) >= 1)
                    {
                        $indexId = 0;
                        $maxId = 0;
                        foreach ($fortuneInfo as $recodeKey => $fortuneStrItem)
                        {
                            $fortuneItem = \GuzzleHttp\json_decode($fortuneStrItem, true);
                            if ((int)$fortuneItem['status'] === 0)
                            {   // 未解锁
                                continue;
                            }

                            if ($recodeKey === $recodeUniqueKey)
                            {
                                $indexId = $fortuneItem['id'];
                            }
                            if ($fortuneItem['id'] > $maxId)
                            {
                                $maxId = $fortuneItem['id'];
                            }
                        }
                        if ($maxId > $indexId)
                        {
                            $isHistory = true;
                        }
                    }
                } else
                {
                    $isHistory = true;
                }
            }
            if ($orders['order_type'] == 5 && !$orders['recode_status'])
            {   // 幸运之城 档案删除 不支持查看
                $isHistory = true;
            }
            if ($orders['order_type'] == 2 && !($orders['recode_info']['status'] ?? false))
            {   // 日运历史
                $isHistory = true;
            }
        }

        $data['target'] = 'local';
        switch ($orders['order_type'])
        {
            case 1:
                $data['link'] = "rectification_details?id={$orders['reid']}";
                break;
            case 2:
                if ($isHistory)
                {
                    $data['link'] = "fortune_for_day_history?need_auth=2&order_id={$orders['order_id']}&rid={$orders['rid']}";
                } else
                {
                    $data['link'] = "day?need_auth=1&rid={$orders['rid']}&time={$orders['time']}";
                }
                break;
            case 3:
                if ($isHistory)
                {
                    $data['link'] = "fortune_for_month_history?need_auth=2&order_id={$orders['order_id']}&rid={$orders['rid']}";
                } else
                {
                    $data['link'] = "fortune_for_month?need_auth=1&rid={$orders['rid']}&time={$orders['time']}";
                }
                break;
            case 4:
                //订单详情年运跳转区分版本
                //1. 修改档案或档案被删除后 【fortune_for_year_history?order_id=订单号&rid=档案ID（可为空）&year=月份(可为空)(历史年运)】
                if ($isHistory)
                {
                    $data['link'] = "fortune_for_year_history?need_auth=0&order_id={$orders['order_id']}&rid={$orders['rid']}";
                } else
                {
                    $data['link'] = "fortune_for_year?need_auth=1&rid={$orders['rid']}&time={$orders['time']}";
                    //2，没有修改的话，
                    // 版本2.9.5 【fortune_for_year_detail?rid=[int,档案ID]&time=[int,年运年份]&need_auth=1【新版本-年运详情】
                    // 老版本 fortune_for_year?rid=参数&time=2018
                    //                    if (Util::CheckAppVersion('2.9.5') === '小')
                    //                    {
                    //                        $data['link'] = "fortune_for_year?need_auth=1&rid={$orders['rid']}&time={$orders['time']}";
                    //                    } else
                    //                    {
                    //                        $data['link'] = "fortune_for_year_detail?rid={$orders['rid']}&time={$orders['time']}&need_auth=1";
                    //                    }
                }
                break;
            case 5:
                if ($isHistory)
                {
                    $data['link'] = "acg_map_history?need_auth=2&order_id={$orders['order_id']}&rid={$orders['rid']}";
                    $data['is_history'] = true;
                } else
                {
                    $data['link'] = "acg_map?need_auth=1&rid={$orders['rid']}";
                }
                break;
            case 6:
                $video = current((new ZhunleCourse())->batchGetInfoByGIds([$orders['gid']]));
                $data['link'] = "course_detail?id={$video['id']}&need_auth=0";
                break;
            case 7:
                $data['link'] = "report_details?need_auth=1&rid={$orders['rid']}&gid={$orders['gid']}&order_id={$orders['order_id']}";
                if (Util::CheckAppVersion('2.6.0') === '小')
                {
                    if (!empty($orders['goods_data']) && count($orders['goods_data']) > 1)
                    {
                        $data['link'] = "report_index?need_auth=1&rid={$orders['rid']}";
                    }
                } else
                {
                    $data['target'] = 'link';
                    $data['link'] = Env::get('host.domain') . "/web/natal_report/index?gid={$orders['gid']}&rid={$orders['rid']}&order_id={$orders['order_id']}&zhunle_not_show_nav=1";
                }
                break;
            case 8:
                $data['link'] = 'vip_center?from=2&need_auth=2';
                break;
            case 15:
                //0=>待支付 1=>问题待审核 2=>问题待接单 3=>问题待解答 4=>解答待审核 5=>已完成待评价 6=>已评价待审核 7=>评价已审核完成 10=>问题审核未通过失效 11=>订单派发超时失效 12=>占星师超时未完成失效 13=>问题待解答（答案审核未通过）14=>占星师拒答两次失效',
                switch ($orders['qstatus'])
                {
                    case 5:
                    case 6:
                    case 7:
                        $data['link'] = "custom_report_result_info?id={$orders['qid']}&type=3&need_auth=2";//已完成
                        break;
                    case 10:
                    case 11:
                    case 12:
                    case 14:
                        $data['link'] = "custom_report_result_info?id={$orders['qid']}&type=4&need_auth=2";//已失效
                        break;
                    default:
                        $data['link'] = "empty";
                        break;
                }
                break;
            case 16:
                $data['link'] = "divination_tarot_detail?id={$orders['qid']}&need_auth=2";
                break;
            case 17:
                if ((int)$orders['status'] === 4)
                {   // 计算成功
                    $synastryReportId = (new ZlSynastryReport())->where('order_num', $orders['order_id'])->value('id');
                    if (is_null($synastryReportId))
                    {
                        $data['target'] = 'toast';
                        $data['link'] = "当前合盘报告结果已删除\r\n不支持查看"; // 如果合盘数据删除了 则不跳转
                    } else
                    {
                        $data['target'] = 'link';
                        $data['link'] = Env::get('host.domain') . "/web/synastry_report/index?id={$synastryReportId}&zhunle_not_show_nav=1&zhunle_nav_text_color=1&need_auth=2";
                    }
                } else
                {
                    $data['target'] = 'toast';
                    $data['link'] = $orders['status_des']; // 如果合盘数据删除了 则不跳转
                }
                break;
            case 18:
                if ((int)$orders['status'] === 4)
                {
                    //查询用户是否测评完成
                    $userTestResult = (new MentalUserRecordModel)->getUserRecrodDetail($orders['uid'], $orders['order_id']);
                    //答题状态 0=> 未开始，1=> 未完成，2=> 已完成
                    if ($userTestResult && 2 === (int)$userTestResult['status'])
                    {//完成了，跳转到 测评结果页，由于安卓有bug，所以改为 直接link跳转结果页
                        //                        $data['link'] = 'mental_test_result?page=mental_test_result&qid=' . $orders['gid'] . '&child_id=' . $orders['extend'] . '&order_id=' . $orders['order_id'];
                        $data['target'] = 'link';
                        $data['link'] = $userTestResult['result_url'];
                    } else
                    {//没有，跳转到 我的测评-未完成页面
                        $data['link'] = 'mental_test_mine?page=mental_test_mine?type=0';
                    }
                } else
                {//跳转到 测评详情页
                    $data['link'] = 'mental_test_detail?page=mental_test_detail&need_auth=2&id=' . $orders['gid'];
                }
                break;
            case 19:
                $data['link'] = "live_answer_detail?id={$orders['fid']}&type=1";
                break;
            case 20:
                $data['link'] = "live_answer_detail?id={$orders['fid']}&type=2";
                break;
            case 21:
                $data['link'] = "live_answer_detail?id={$orders['fid']}&type=3";
                break;
            case 22:
                if ($orders['status'] == 2)
                {
                    $data['link'] = 'app_tab?type=2';
                } else
                {
                    $data['link'] = "question_detail?qid={$orders['fid']}&comment_id=0&is_answer_detail=0&need_auth=0";
                }
                break;
            case 23:
                $data['target'] = 'link';
                $data['link'] = $host . "/web/relation_research_fit_you/index?rid={$orders['recode']['id']}&order_id={$orders['order_id']}&tab_gid={$orders['gid']}&need_auth=1&zhunle_not_show_nav=1&zhunle_nav_text_color=1";
                break;
            case 24:
                $info = Zl1RelationAnalysisIdea::withTrashed()->where('order_num', $orders['order_id'])->field('id')->find();
                $data['link'] = $info ? 'relation_research_ideal_result?id=' . $info['id'] . '&need_auth=2' : '';
                break;
            case 25:
                $data['target'] = 'link';
                $data['link'] = $host . "/web/relation_research_fit_you/follow?order_id={$orders['order_id']}&rid1={$orders['extend']['recode_ids']['rid1']}&rid2={$orders['extend']['recode_ids']['rid2']}&need_auth=0&zhunle_not_show_nav=1&zhunle_nav_text_color=1";
                break;
            case 26:
                $data['target'] = 'link';
                $recode = current($orders['recode']);
                $data['link'] = $host . "/web/relation_research_fit_you/check_player?order_id={$orders['order_id']}&rid={$recode['id']}&need_auth=0&zhunle_not_show_nav=1&zhunle_nav_text_color=1";
                break;
            case 27:
                if ((int)$orders['gid'] === 91)
                {
                    $data['link'] = "fortune_stage?rid={$orders['extend']['recode_info']['id']}&year={$orders['extend']['year_life']['start_time']}&order_id={$orders['order_id']}&need_auth=1";
                } elseif ((int)$orders['gid'] === 92)
                {
                    $data['link'] = "fortune_screening?rid={$orders['extend']['recode_info']['id']}&order_id={$orders['order_id']}&need_auth=1";
                } else
                {
                    $data['link'] = 'empty';
                }
                break;
            case 28:
                $data['target'] = 'local';
                $recode = current($orders['recode']);
                if (Goods::isBaziJsjr(28, $orders['gid']))
                {
                    $historyId = (new Zl4HoroscopeGoodTime())->where('order_num', $orders['order_id'])->value('id');
                    $data['link'] = "horoscope_select_time_detail?id={$historyId}&need_auth=1";
                } //用神
                elseif ((int)$orders['gid'] === 106)
                {
                    $data['link'] = "horoscope_yongshen_info?rid={$recode['id']}&order_id={$orders['order_id']}&need_auth=1";
                } //72格局
                elseif ((int)$orders['gid'] === 107)
                {
                    $data['link'] = "horoscope_pattern_72_info?rid={$recode['id']}&order_id={$orders['order_id']}&need_auth=1";
                }
                break;
            case 29:
                $mid = array_keys($orders['extend']['meditation'])[0];
                $sign = $orders['extend']['meditation'][$mid]['in_sign'];
                $data['link'] = "meditate_detail?id={$mid}&sign={$sign}&need_auth=0";
                break;
            case 32:
                $data['link'] = "acquired_astro_index?pay_suc=0&need_auth=0";
                break;
            case 35:
                if (in_array($orders['status'], [1, 4], false))
                {
                    $data['target'] = 'flutter';
                    if ((int)$orders['gid'] === 164)
                    {
                        $data['link'] = "name_rate_detail_page?id={$orders['extend']['history']['id']}";
                    } else
                    {
                        $data['link'] = "name_start_detail_page?id={$orders['extend']['history']['id']}";
                    }
                }
                break;
            default:
                $data['link'] = 'empty';
                break;
        }
        return $data;
    }

    /**
     * 获取支付方式描述
     * @param int $tradeType
     * @return string
     */
    public function tradeTypeDes($tradeType)
    {
        switch ($tradeType)
        {
            case 1:
            case 7:
                $tradeTypeDes = '支付宝支付';
                break;
            case 2:
            case 6:
            case 8:
            case 13:
            case 15:
                $tradeTypeDes = '微信支付';
                break;
            case 4:
                if (Util::IsIos() && Util::CheckAppVersion('11.0.0') !== '小')
                {
                    $tradeTypeDes = 'Z币支付';
                } else
                {
                    $tradeTypeDes = '准币支付';
                }
                break;
            case 9:
                $tradeTypeDes = '苹果支付';
                break;
            default:
                $tradeTypeDes = '未知的支付';
                break;
        }
        return $tradeTypeDes;
    }

    /**
     * 获取下单环境描述
     * @param $envType
     * @return string|null
     */
    public function envTypeDes($envType)
    {
        //下单环境 1=>app,2=>微信小程序,3=>抖音小程序,4=>支付宝小程序,5=>百度小程序,6=>QQ小程序,7=>H5
        switch ($envType)
        {
            case 2:
                $mini_type_des = '（微信）';
                break;
            case 3:
                $mini_type_des = '（抖音）';
                break;
            case 4:
                $mini_type_des = '（支付宝）';
                break;
            case 5:
                $mini_type_des = '（百度）';
                break;
            case 6:
                $mini_type_des = '（QQ）';
                break;
            case 7:
                $mini_type_des = '（h5）';
                break;
            default:
                $mini_type_des = null;
                break;
        }
        return $mini_type_des;
    }

    /**
     * 获取档案变动信息
     * @param $backRecodeInfo
     * @param $recode
     * @return array
     */
    protected function getRecodeDiffInfo($backRecodeInfo, $recode)
    {
        $recodeInfo = [];
        foreach ($backRecodeInfo as $item)
        {
            if (!$item)
            {
                continue;
            }
            $tmp = is_string($item) ? json_decode($item, true) : $item;
            $recode1 = (new Recode())->getRecodeInfoStr($tmp);
            $recode2 = (new Recode())->getRecodeInfoStr($recode[$tmp['id']]);
            if ($recode1 !== $recode2)
            {
                $recode_diff = '订单已经发生修改';
            }
            $recodeInfo[] = $tmp;
        }
        return ['recode_info' => $recodeInfo, 'recode_diff' => $recode_diff ?? ''];
    }

    /**
     * 获取订单列表按钮
     * @param $order
     * @return array|array[]|mixed
     */
    public function getIndexOrderBtn($order)
    {
        // 如果是苹果支付，并且是未支付的情况，去支付在按钮不显示
        if ((int)$order['status'] === 0)
        {
            if ((int)$order['trade_type'] === 9)
            {
                return [];
            }
            //修复IOS订单列表支付密码双重加密问题
            if (Util::IsIos() && Util::CheckAppVersion('2.10.0') === '小')
            {
                return [];
            }
        }

        $btns = config('zhunleorder');
        $orderBtn = $btns['index_order_btn'][$order['status']] ?? [];
        //获取首页按钮配置
        switch ($order['order_type'])
        {
            case 14:
                if ($order['status'])
                {
                    return $btns['mall_order_btn'][$order['status']];
                } else
                {
                    return [];
                }
            case 2:
            case 3:
            case 4:
            case 7:
            case 8:
            case 9:
            case 10:
            case 15:
            case 16:
            case 17:
            case 1:
            case 5:
            case 6:
            case 18:
            case 19:
            case 20:
            case 21:
            case 22:
            case 23:
            case 24:
            case 25:
            case 26:
            case 27:
            case 28:
                return $orderBtn;
        }
        return $orderBtn;
    }

    /**
     * 获取订单详情按钮
     * @param $order
     * @return array|array[]|mixed
     * @throws Exception
     */
    public function getDetailOrderBtn($order)
    {
        $btns = config('zhunleorder');
        $orderBtn = $btns['read_order_btn'][$order['status']] ?? [];
        switch ($order['order_type'])
        {
            case 1: //订单关闭，等待支付，等待计算（校准生辰）不可跳转
            case 5:
            case 6:
                if (in_array((int)$order['status'], [3, 4], true))
                {
                    return [];
                }
                break;
            case 2:
            case 3:
            case 4:
            case 7:
            case 8:
            case 9:
            case 10:
            case 14:
            case 15:
            case 16:
            case 17:
                return $orderBtn;
            case 18:
                return [];
            case 19:
            case 20:
            case 21:
                if (in_array($order['status'], [1, 4], false))
                {
                    $typeName = '';
                    switch ($order['order_type'])
                    {
                        case 19:
                            $typeName = '看盘详情';
                            break;
                        case 20:
                            $typeName = '骰子详情';
                            break;
                        case 21 :
                            $typeName = '塔罗详情';
                            break;
                    }
                    $orderBtn = [
                        [
                            'name' => $typeName,
                            'type' => 10,
                        ],
                    ];
                } elseif (in_array((int)$order['status'], [2, 3], true))
                {
                    $orderBtn = [];
                }
                break;
            case 22:
                if (in_array($order['status'], [2, 3, 4], false))
                {
                    $orderBtn = [];
                } elseif ($order['status'] == 1)
                {
                    $question = (new Zlcr2UserQuestion())->getInfoById($order['fid'], ['status']);
                    if (in_array($question['status'], [1, 2], true))
                    {
                        //问题已支付待接单均可以取消
                        $orderBtn = [
                            [
                                'name' => '取消订单',
                                'type' => 4,
                            ],
                        ];
                    }
                }
                break;
            case 23:
            case 24:
            case 25:
            case 26:
            case 27:
            case 28:
            case 29:
            case 30:
            case 31:
            case 32:
                if ($order['status'])
                {
                    $orderBtn = [];
                }
                break;
        }
        return $orderBtn;
    }

    ############################################## todo 版本2.7.0之前的下单逻辑 ################################################

    /**
     * 获取订单状态的描述
     * @param $orders
     * @return mixed
     * @throws Exception
     */
    public function ordersDetail($orders)
    {
        //订单关闭，等待支付，等待计算（校准生辰）不可跳转
        $btns = config('zhunleorder');
        if (in_array($orders['order_type'], [19, 20, 21], false))
        {
            $valid_time = $orders['create_time'] + $btns['close_answer_time'];//5分钟未支付关闭订单
        } else
        {
            $valid_time = $orders['create_time'] + $btns['close_order_time'];//30分钟未支付关闭订单
        }
        //订单剩余关闭时间
        $time_remaining = $valid_time - time();
        $time_remaining = $time_remaining > 0 ? $time_remaining : 0;
        $orders['time_remaining'] = 0;
        $orders['des'] = '';
        $orders['is_skip'] = 1;//订单内是否可以跳转
        $orders['is_display_recommend_data'] = 0;//是否显示推荐商品
        $extend = $orders['extend'] ? json_decode($orders['extend'], true) : [];
        $order_coupon = $extend['coupon'] ?? [];//获取订单的优惠券信息
        $order_active = $extend['active'] ?? [];//获取订单的活动信息
        if (isset($extend['mall']) && $extend['mall'])
        {
            $mallInfo = $extend['mall'];
        } elseif ($extend)
        {
            $mallInfo = $extend;
        } else
        {
            $mallInfo = [];
        }
        $orders['history'] = $extend['history'] ?? [];//获取订单相关的历史记录信息
        //订单优惠券信息
        $orders['coupon_data'] = [];
        if ($order_coupon)
        {
            $orders['coupon_data'] = [
                'name' => $order_coupon['name'],
                'title' => $order_coupon['title'],
                'discount_price' => sprintf('%.2f', $order_coupon['discount_price']),
            ];
        }
        //订单活动信息
        $orders['active_data'] = [];
        if ($order_active)
        {
            $orders['active_data'] = [
                'name' => $order_active['name'],
                'discount_price' => sprintf('%.2f', $order_active['discount_price']),
            ];
        }
        //未支付订单，处理订单关闭状态
        if ($orders['status'] == 0)
        {
            $orders['status'] = $time_remaining ? $orders['status'] : 2;
        }
        //修改小程序下单的支付方式
        if ($orders['trade_type'] == 13 || $orders['trade_type'] == 8 || $orders['trade_type'] == 15)//微信
        {
            $orders['trade_type'] = 2;
        } elseif ($orders['trade_type'] == 7)//支付宝
        {
            $orders['trade_type'] = 1;
        }
        switch ($orders['status'])
        {
            case 0:
                $orders['status_des'] = '等待支付';
                $orders['des'] = '请在' . (int)($btns['close_order_time'] / 60) . '分钟内完成支付';
                $orders['time_remaining'] = $time_remaining;
                $orders['is_skip'] = 0;
                break;
            case 1:
                //若是有队列的商品，则增加订单描述
                if (in_array($orders['order_type'], [1, 3, 4, 5, 7, 15, 17], false))
                {
                    $orders['des'] = '购买成功后，24小时内会给您预测结果';
                    $orders['status_des'] = '预测进行中';
                } elseif (in_array($orders['order_type'], [19, 20, 21], false))
                {
                    $orders['des'] = '主播会在直播间为你解答';
                    $orders['status_des'] = '等待解答中';
                } elseif ($orders['order_type'] == 14)
                {
                    $orders['status_des'] = '待发货';
                } elseif ($orders['order_type'] == 22)
                {
                    $orders['status_des'] = '订单进行中';
                } else
                {
                    $orders['status_des'] = '订单完成';
                }
                if ($orders['order_type'] == 1)
                {
                    $orders['is_skip'] = 0;
                }
                break;
            case 2:
                $orders['status_des'] = '订单关闭';
                $orders['is_display_recommend_data'] = 1;
                $orders['is_skip'] = 0;
                if ((int)$orders['order_type'] === 18)
                {
                    $orders['is_skip'] = 1;
                }
                $orders['total_amount'] = '0.00';
                break;
            case 3:
                $orders['status_des'] = '退款成功';
                $orders['is_skip'] = 0;
                break;
            case 4:
                $orders['status_des'] = '订单已完成';
                $orders['is_display_recommend_data'] = 1;
                break;
            case 5:
                $orders['status_des'] = '待收货';
                $kdTime = $mallInfo['kd_send_time'] ?? $orders['pay_time'];
                $fifTime = strtotime('+15days', $kdTime);
                if (time() > $fifTime)
                {
                    $orders['des'] = '订单已完成';
                    $orders['status'] = 4;
                    $orders['status_des'] = '订单已完成';
                    $this->UpdateData($orders['order_id'], ['status' => 4], 4);
                } else
                {
                    $mallTime = (new Util())->timediff(time(), dateModify('U', $kdTime, '+15days'));
                    $orders['des'] = $mallTime['day'] . '天' . $mallTime['hour'] . '小时' . $mallTime['min'] . '分钟后自动确认收货';
                }
                break;
        }
        //下单环境
        $orders['mini_type_des'] = $this->envTypeDes($orders['env_type']);
        //支付类型
        $orders['trade_type_des'] = $this->tradeTypeDes($orders['trade_type']);
        //获取退款信息
        $refundInfo = (new AppOrdersRefund())->getInfoById($orders['order_id']);
        if ($refundInfo)
        {
            $orders['refund_data'] = [
                'name' => '退款',
                'price' => $refundInfo['refund_price'],
            ];
        } else
        {
            $orders['refund_data'] = null;
        }
        return $orders;
    }

    /**
     * 校准生辰详情
     * @param $orders
     * @return array
     * @throws Exception
     */
    public function RecRead($orders)
    {
        $arr = [];
        //获取商品信息
        $arr['goods_data'] = (new Goods())->batchGetInfoByIds($orders['gid']);
        //获取校准生辰信息
        $arr['data'] = (new Rectification())->getInfoById($orders['reid']);
        //获取档案信息
        $arr['recode_data'] = (new Recode())->batchGetInfoByIds($arr['data']['rid']);
        return $arr;
    }

    /**
     * 运势详情
     * @param array $orders
     * @return array|Json
     * @throws Exception
     */
    public function FortuneRead($orders)
    {
        //获取商品信息
        $arr['goods_data'] = (new Goods())->batchGetInfoByIds($orders['gid']);
        $goods = $arr['goods_data'] ? current($arr['goods_data']) : [];
        $fortune = current((new Fortune())->batchGetInfo([$orders['fid']]));
        $extend = json_decode($orders['extend'], true);
        //判断该笔订单是否是活动期间购买的
        if (isset($extend['expire_time']) && $extend['expire_time'])
        {
            $goods['expire_time'] = $extend['expire_time'];
        }
        $arr['fortune_data']['fortune_type'] = $fortune['type'];
        $arr['fortune_data']['rids'] = $fortune['rids'];
        $arr['fortune_data']['start_time'] = date('Y-m-d', $fortune['time']);
        $arr['fortune_data']['end_time'] = date('Y-m-d', strtotime($goods['expire_time'], $fortune['time']) - 86400);
        //获取运势信息
        switch ($orders['order_type'])
        {
            case 3:
                $arr['fortune_data']['start_time'] = date('Y-m', $fortune['time']);
                $arr['fortune_data']['end_time'] = date('Y-m', strtotime($goods['expire_time'], $fortune['time']) - 86400);
                $fortuneBackInfo = (new MonthFortune())->getOrderRecodeBackRecode($orders['order_id']);
                break;
            case 4:
                $arr['fortune_data']['start_time'] = date('Y', $fortune['time']);
                $arr['fortune_data']['end_time'] = date('Y', strtotime($goods['expire_time'], $fortune['time']) - 86400);
                $fortuneBackInfo = (new YearFortune())->getOrderRecodeBackRecode($orders['order_id']);
                break;
        }
        $arr['recode_data'] = [];
        if (!empty($fortuneBackInfo))
        {
            foreach ($fortuneBackInfo as $item)
            {
                $recodeItem = json_decode($item, true);
                $recodeStatus = (new Recode())->getInfoById($recodeItem['id'], ['status']);
                $recodeItem['status'] = $recodeStatus['status'];
                $arr['recode_data'][] = $recodeItem;
            }
        } else
        {
            $arr['recode_data'] = (new Recode())->batchGetInfoByIds($fortune['rids']);
        }
        return $arr;
    }

    /**
     * 地图详情和本命报告
     * @param array $orders
     * @return array
     * @throws Exception
     */
    public function MapRead($orders)
    {
        //获取商品信息
        $maps_goods = current((new OrdersGoods())->batchGetInfo([$orders['id']])) ?: [];
        $rids = [];
        $gids = [];
        foreach ($maps_goods as $order_good)
        {
            $og = json_decode($order_good, true);
            $rids[] = $og['rid'];
            $gids[] = $og['gid'];
        }
        $arr['goods_data'] = (new Goods())->batchGetInfoByIds($gids);
        if (in_array(19, $gids, false))
        {
            $goodsName = '幸运之城';
            $goodsDes = '幸运之城全内容打包解锁';
        } else
        {
            $goodsDes = implode('、', array_column($arr['goods_data'], 'name'));
        }
        $price = 0;
        foreach ($arr['goods_data'] as $good)
        {
            $price += $good['now_prize'];
        }
        $goodsPrice = $price;
        $arr['data'] = [
            'name' => $goodsName ?? '',
            'des' => $goodsDes,
            'price' => $goodsPrice,
        ];
        if ($orders['order_type'] == 5)
        {
            //获取档案信息
            $resultIds = (new MapUnlockResult())->getUnlockIdsFromCache(1, $orders['order_id']);
            $resultInfo = (new MapUnlockResult())->batchGetInfoByIds($resultIds, ['rid_back']);
            $backRecodeInfo = (new MapRecodeBack())->batchGetInfoByIds(array_column($resultInfo, 'rid_back'));

        } else
        {
            // 0=>未支付  1=>等待计算|等待矫正| 等待发货  2=>交易关闭   3=>退款成功  4=>计算成功|矫正成功|已支付  5=>等待收货
            $backRecodeInfo = (new NatalReport())->getOrderRecodeBackRecode($orders['order_id']);
        }
        $arr['recode_data'] = [];
        if (!empty($backRecodeInfo))
        {
            foreach ($backRecodeInfo as $item)
            {
                $arr['recode_data'][] = json_decode($item, true);
            }
        } else
        {
            $arr['recode_data'] = (new Recode())->batchGetInfoByIds($rids);
        }
        return $arr;
    }

    /**
     * 视频详情
     * @param array $orders
     * @return array
     * @throws Exception
     */
    public function VideoRead($orders)
    {
        //获取商品信息
        $arr['goods_data'] = (new Goods())->batchGetInfoByIds($orders['gid']);
        $video_title = (new ZhunleCourse())->batchGetInfoByGIds($orders['gid'], ['id', 'title']);
        $video_title = $video_title ? current($video_title) : [];
        $arr['video_id'] = (int)$video_title['id'];
        $arr['goods_data_des'] = $video_title['title'];
        return $arr;
    }

    /**
     * vip详情
     * @param $orders
     * @return array
     * @throws Exception
     */
    public function VipRead($orders)
    {
        //获取商品信息
        $arr['goods_data'] = (new Goods())->batchGetInfoByIds($orders['gid']);
        $goods = $arr['goods_data'] ? current($arr['goods_data']) : [];
        $goods_extend = $goods['extend'] ? json_decode($goods['extend'], true) : [];
        //获取商品描述
        if (Util::CheckAppVersion('2.9.7') === '大' && Util::IsIos())
        {
            $goodsDes = $goods_extend['ios_goods_des'] ?? '';
        } else
        {
            $goodsDes = $goods_extend['goods_des'] ?? '';
        }
        $arr['goods_data_des'] = $goodsDes;
        //获取用户当前vip有效时间
        $extend = $orders['extend'] ? json_decode($orders['extend'], true) : [];
        $vip_start_time = $extend['vip_start_time'] ?? 0;
        $vip_end_time = $extend['vip_end_time'] ?? 0;
        $arr['vip_start_time'] = $vip_start_time ? date('Y-m-d', $vip_start_time) : '';
        $arr['vip_end_time'] = $vip_end_time ? date('Y-m-d', $vip_end_time) : '';
        return $arr;
    }

    /**
     * 商城详情
     * @param $orders
     * @return mixed
     * @throws Exception
     */
    public function MallRead($orders)
    {
        $arr['extend'] = $this->getMallExtend($orders);
        $gid = $arr['extend']['mall_gid'];
        $num = $arr['extend']['num'];
        //获取商品信息
        $arr['goods_data'] = current((new MallGoods())->batGetInfo([$gid]));
        //获取商品规格信息
        $arr['spec_info'] = current((new MallGoodsAttr())->batGetInfo([$orders['gid']]));
        //获取商品描述
        $arr['goods_data_des'] = '商品规格：' . $arr['spec_info']['name'] . ' x' . $num;
        return $arr;
    }

    /**
     * 获取商城订单extend数据
     * @param $orders
     * @return array|array[]|mixed
     */
    public function getMallExtend($orders)
    {
        $extend = $orders['extend'] ? json_decode($orders['extend'], true) : [];
        if (!isset($extend['mall']['mall_gid']))
        {
            $mallExtend = [
                'address' => $extend['address'],
                'is_faraway' => $extend['is_faraway'],
                'phone' => $extend['phone'],
                'name' => $extend['name'],
                'kd_price' => $extend['kd_price'],
                'mall_gid' => $extend['mall_gid'],
                'num' => $extend['num'],
                'remark' => $extend['remark'],
                'kd_id' => $extend['mall']['kd_id'] ?? $extend['kd_id'],
                'kd_name' => $extend['mall']['kd_name'] ?? $extend['kd_name'],
                'kd_send_time' => isset($extend['mall']['kd_send_time']) ? date('Y-m-d H:i:s', $extend['mall']['kd_send_time']) : '',
            ];
        } else
        {
            $mallExtend = $extend['mall'];
        }
        return $mallExtend;

    }

    /**
     * 定制报告详情
     * @param $orders
     * @return array
     * @throws Exception
     */
    public function CustomReport($orders)
    {
        $customReportModel = new ZlcrCustomReportQuestion();
        $customReportResultModel = new ZlcrCustomReportQuestionInfo();
        $questionGoodsModel = new ZlcrCustomReportGoods();
        $questionInfo = $customReportModel->getOrderNumQuestionFromCache($orders['order_id']);
        //获取报告状态和跳转地址
        $questionInfo['status_link'] = $customReportModel->getReportStateDes($questionInfo);
        $questionResultInfo = $customReportResultModel->getInfoById($questionInfo['id']);
        $backRecodeInfo = !empty($questionResultInfo) ? json_decode($questionResultInfo['recode_info'], true) : [];
        foreach ($backRecodeInfo as $key => $recodeItem)
        {
            if (!$recodeItem)
            {
                continue;
            }
            $recodeStatus = (new Recode())->getInfoById($recodeItem['id'], ['status']);
            $backRecodeInfo[$key]['status'] = $recodeStatus['status'];
        }
        $goodsInfo = $questionGoodsModel->getInfoById($questionInfo['gid']);
        return ['recode_data' => $backRecodeInfo, 'question_data' => $questionInfo, 'goods_data' => $goodsInfo];
    }

    /**
     * 获取塔罗详情
     * @param $orders
     * @return mixed
     * @throws Exception
     */
    public function tarot($orders)
    {
        $extend = $orders['extend'] ? json_decode($orders['extend'], true) : [];
        if (isset($extend['history']))
        {
            $arr['history'] = $extend['history'];
        } else
        {
            $arr['history'] = [];
        }
        $arr['goods_data'] = (new Goods())->batchGetInfoByIds([$orders['gid']]);
        return $arr;
    }

    /**
     * 获取合盘报告详情
     * @param $orders
     * @return array
     * @throws Exception
     */
    public function SynastryReport($orders)
    {
        $extend = $orders['extend'] ? json_decode($orders['extend'], true) : [];
        if (isset($extend['synastry_report']))
        {
            $synastry_report = $extend['synastry_report'];
        } else
        {
            $synastry_report = [
                'rid1' => 0,
                'rid2' => 0,
                'sid' => 0,
                'relation_id' => 0,
            ];
        }
        $reportInfo = (new ZlSynastryReport())->getOrderRecodeBackRecode($orders['order_id']);
        if ($reportInfo)
        {
            //获取合盘报告备份档案信息
            $recodeInfo = array_values(json_decode(current($reportInfo), true));

            foreach ($recodeInfo as $key => $item)
            {
                $recodeStatus = (new Recode())->getInfoById($item['id'], ['status']);
                $recodeInfo[$key]['status'] = $recodeStatus['status'];
            }
        } else
        {
            $recodeInfo = (new Recode())->batchGetInfoByIds([$synastry_report['rid1'], $synastry_report['rid2']]);
        }
        $relationConfig = config('synastryreport')[$synastry_report['srid']]['relation_list'];
        $relationInfo = $relationConfig[$synastry_report['relation_id']] ?? '';
        //获取商品信息
        $goodsInfo = (new Goods())->batchGetInfoByIds($orders['gid']);
        return ['recode_data' => $recodeInfo, 'relation_data' => $relationInfo, 'goods_data' => $goodsInfo];
    }

    /**
     * 心理测试详情
     * @param $orders
     * @return mixed
     * @throws Exception
     */
    public function MentalTestDetail($orders)
    {
        //校验问题id
        $mentalQuestionModel = new MentalQuestionModel();
        $question = $mentalQuestionModel->getQuestionDetailById($orders['gid']);
        if (!$question)
        {
            return show(config('code.error'), '测评问题不存在！');
        }
        $valids = MentalTestUtil::validChildId($question, $orders['extend']);

        if (!$valids[0])
        {
            return show(config('code.error'), '问题id和解锁id不一致！');
        }
        return $valids[1] ?: $question;
    }

    ############################################## todo 版本2.7.0开始的新版下单逻辑 ################################################

    /**
     * 获取订单状态的描述
     * @param $order
     * @return mixed
     * @throws Exception
     */
    public function ordersDetail2(&$order)
    {
        $order['trade_type'] = (int)$order['trade_type'];
        $order['des'] = '';
        $order['is_skip'] = 1;//订单内是否可以跳转
        //获取订单拓展字段
        $extend = $order['extend'] ? json_decode($order['extend'], true) : [];
        $order['coupon_data'] = $extend['coupon'] ?? [];//获取订单的优惠券信息
        $order['active'] = $extend['active'] ?? [];//获取订单的活动信息
        $order['new_active'] = $extend['new_active'] ?? [];//获取订单的活动信息新版
        $order['synastry_report'] = $extend['synastry_report'] ?? [];//获取订单的合盘报告信息
        $order['live_info'] = $extend['live_info'] ?? [];//获取订单的直播间主播信息
        if (!empty($extend['mall']))
        {
            $order['mall'] = $extend['mall'];
        } elseif ($extend)
        {
            $order['mall'] = $extend;
        } else
        {
            $order['mall'] = [];
        }
        $order['history'] = $extend['history'] ?? [];//获取订单相关的历史记录信息

        //获取订单状态描述信息
        $this->statusDesInfo($order);

        //修改小程序下单的支付方式
        if ($order['trade_type'] === 13 || $order['trade_type'] === 8 || $order['trade_type'] === 15)//微信
        {
            $order['trade_type'] = 2;
        } elseif ($order['trade_type'] === 7)//支付宝
        {
            $order['trade_type'] = 1;
        }
        //下单环境
        $order['mini_type_des'] = $this->envTypeDes($order['env_type']);
        //支付类型
        $order['trade_type_des'] = $this->tradeTypeDes($order['trade_type']);

        //获取退款信息
        $refundInfo = (new AppOrdersRefund())->getInfoById($order['order_id']);
        if ($refundInfo)
        {
            $order['refund_data'] = [
                'name' => '退款',
                'price' => $refundInfo['refund_price'],
            ];
        } else
        {
            $order['refund_data'] = null;
        }

        //组合订单详情页面下方信息
        $order['order_data'][] = [
            'name' => '下单时间',
            'value' => date('Y-m-d H:i:s', $order['create_time']),
            'is_copy' => 0,
        ];
        $order['order_data'][] = [
            'name' => '订单编号',
            'value' => $order['order_id'],
            'is_copy' => 1,
        ];
        if ($order['live_info'])
        {
            $order['order_data'][] = [
                'name' => '下单直播间',
                'value' => $order['live_info']['name'],
                'is_copy' => 0,
            ];
        }
        // 苹果支付不显示支付方式
        if ($order['trade_type'] !== 9)
        {
            $order['order_data'][] = [
                'name' => '支付方式',
                'value' => $order['trade_type_des'],
                'is_copy' => 0,
            ];
        }
        if ($order['pay_time'])
        {
            $order['order_data'][] = [
                'name' => '支付时间',
                'value' => date('Y-m-d H:i:s', $order['pay_time']),
                'is_copy' => 0,
            ];
        }
        //退款信息
        if ($order['status'] == 3)
        {
            $refund = (new AppOrdersRefund())->getInfoById($order['order_id']);
            if ($refund)
            {
                $refundTotal = $refund['refund_price'];
                if ((int)$order['trade_type'] === 4)
                {
                    $refundTotal = \app\common\cachemodel\OrdersLib::getOrderCoinNum($refund['refund_price']) . '币';
                }
                $order['order_data'][] = [
                    'name' => '退款金额',
                    'value' => $refundTotal,
                    'is_copy' => 0,
                ];
                $order['order_data'][] = [
                    'name' => '退款时间',
                    'value' => date('Y-m-d H:i:s', $refund['create_time']),
                    'is_copy' => 0,
                ];
            }
        }

        //获取用户准币信息
        if ((int)$order['status'] === 0)
        {
            $user_coin = (new ZhunleUserAccount())->getUserCoinFromCache($order['uid']);
            $order['coin_num'] = (int)($user_coin['balance'] ?? 0);
            $order['pwd_status'] = (isset($user_coin['password']) && $user_coin['password']) ? 1 : 0;
        }
        return $order;
    }

    /**
     * 校准生辰详情
     * @param $order
     * @throws Exception
     */
    public function RecRead2(&$order)
    {
        //获取商品信息
        $order['goods'] = (new Goods())->batchGetInfoByIds($order['gid']);

        //重组订单拓展信息
        $this->orderGoodsActive($order);

        //获取校准生辰信息
        $order['rec'] = (new Rectification())->getInfoById($order['reid']);
        //获取校正事件信息
        $order['rectification_data']['des1'] = date('Y-m-d', $order['rec']['start_time']);
        $order['rectification_data']['des2'] = date('H:i', $order['rec']['start_time']) . '至' . ((date('d', $order['rec']['start_time']) != date('d', $order['rec']['end_time'])) ? '次日' : '') . date('H:i', $order['rec']['end_time']);
        //获取校准生辰事件信息
        $events = (new RectificationEvent())->batchGetInfoByIds($order['reid'], [
            'id',
            'status',
            'reid',
            'time',
            'type',
            'desc',
        ]);
        foreach ($events as $k => $event)
        {
            unset($event['status'], $event['reid']);
            $event['time'] = $event['time'] ? date('Y-m', $event['time']) : '';
            $events[$k] = $event;
        }
        $order['rectification_data']['event'] = $events;

        //获取档案信息
        $order['recode'] = (new Recode())->batchGetInfoByIds($order['rec']['rid']);
        $recodeData = [];
        foreach ($order['recode'] as $item)
        {
            if (!$item['status'])
            {
                Util::orderBtnReset($order['order_btn']);
            }
            $recodeData[] = (new Recode())->recodeInfoFormat($item);
        }
        if ($recodeData)
        {
            $order['recode_data']['des'] = implode(',', array_column($recodeData, 'name'));
            $order['recode_data']['info'] = $recodeData;
        }

        //获取订单跳转信息
        if ((int)$order['status'] === 4 && $order['is_skip'])
        {
            if (current($order['recode'])['status'])
            {
                $targetInfo = $this->orderTypeLink($order);
            } else
            {
                $targetInfo['target'] = 'toast';
                $targetInfo['link'] = "当前档案已删除\r\n不支持查看"; // 如果档案删除了 则不跳转
            }
        } else
        {
            $targetInfo['target'] = 'local';
            $targetInfo['link'] = 'empty';
        }

        $order['target'] = $targetInfo['target'];
        $order['link'] = $targetInfo['link'];
        array_walk($order['goods_data'], static function (&$v, $k, $p)
        {
            $v = array_merge($v, $p);
        }, ['target' => $order['target'], 'link' => $order['link'], 'rname' => '']);
    }

    /**
     * 运势详情
     * @param $order
     * @throws Exception
     */
    public function FortuneRead2(&$order)
    {
        //获取商品信息
        $order['goods'] = (new Goods())->batchGetInfoByIds($order['gid']);
        //获取运势信息
        $order['fortune'] = current((new Fortune())->batchGetInfo([$order['fid']]));

        //重组订单拓展信息
        $this->orderGoodsActive($order);

        //获取运势信息
        switch ($order['order_type'])
        {
            case 3:
                $fortuneBackInfo = (new MonthFortune())->getOrderRecodeBackRecode($order['order_id']);
                break;
            case 4:
                $fortuneBackInfo = (new YearFortune())->getOrderRecodeBackRecode($order['order_id']);
                break;
        }
        $order['recode'] = (new Recode())->batchGetInfoByIds($order['fortune']['rids']);
        if (!empty($fortuneBackInfo))
        {
            $order['recode'] = [];
            foreach ($fortuneBackInfo as $item)
            {
                $recodeItem = json_decode($item, true);
                $recodeStatus = (new Recode())->getInfoById($recodeItem['id'], ['status']);
                $recodeItem['status'] = $recodeStatus['status'];
                $order['recode'][] = $recodeItem;
            }
        }
        $recodeData = [];
        foreach ($order['recode'] as $item)
        {
            if (!$item['status'])
            {
                Util::orderBtnReset($order['order_btn']);
            }
            $recodeData[] = (new Recode())->recodeInfoFormat($item);
        }

        if ($recodeData)
        {
            $order['recode_data']['des'] = implode(',', array_column($recodeData, 'name'));
            $order['recode_data']['info'] = $recodeData;
        }

        //获取订单跳转信息
        if ((int)$order['status'] === 4 && $order['is_skip'])
        {
            $order['rid'] = current($order['recode'])['id'];
            $order['recode_info'] = current($order['recode']);
            $order['time'] = current($order['goods_data'])['start_time'];
            $targetInfo = $this->orderTypeLink($order);
        } else
        {
            $targetInfo = ['target' => 'local', 'link' => 'empty'];
        }
        $order['target'] = $targetInfo['target'];
        $order['link'] = $targetInfo['link'];
        array_walk($order['goods_data'], static function (&$v, $k, $p)
        {
            $v = array_merge($v, $p);
        }, ['target' => $order['target'], 'link' => $order['link'], 'rname' => current($order['recode'])['name']]);
    }

    /**
     * 地图详情和本命报告
     * @param $order
     * @throws Exception
     */
    public function MapRead2(&$order)
    {
        //获取商品信息
        $maps_goods = current((new OrdersGoods())->batchGetInfo([$order['id']])) ?: [];
        $rids = [];
        $gids = [];
        foreach ($maps_goods as $order_good)
        {
            $og = json_decode($order_good, true);
            $rids[] = $og['rid'];
            $gids[] = $og['gid'];
        }
        $order['goods'] = (new Goods())->batchGetInfoByIds($gids);

        //重组订单拓展信息
        $this->orderGoodsActive($order);

        //组合订单档案信息
        if ($order['order_type'] == 5)
        {
            $resultIds = (new MapUnlockResult())->getUnlockIdsFromCache(1, $order['order_id']);
            $resultInfo = (new MapUnlockResult())->batchGetInfoByIds($resultIds, ['rid_back']);
            $backRecodeInfo = (new MapRecodeBack())->batchGetInfoByIds(array_column($resultInfo, 'rid_back'));

        } else
        {
            // 0=>未支付  1=>等待计算|等待矫正| 等待发货  2=>交易关闭   3=>退款成功  4=>计算成功|矫正成功|已支付  5=>等待收货
            $backRecodeInfo = (new NatalReport())->getOrderRecodeBackRecode($order['order_id']);
        }
        $order['recode'] = $recodeData = [];
        if (!empty($backRecodeInfo))
        {
            foreach ($backRecodeInfo as $item)
            {
                $order['recode'][] = $tmpRecode = json_decode($item, true);
                if (isset($tmpRecode['status']) && !$tmpRecode['status'])
                {
                    Util::orderBtnReset($order['order_btn']);
                }
                $recodeData[] = (new Recode())->recodeInfoFormat($tmpRecode);
            }
        } else
        {
            $order['recode'] = (new Recode())->batchGetInfoByIds($rids);
            foreach ($order['recode'] as $item)
            {
                if (!$item['status'])
                {
                    Util::orderBtnReset($order['order_btn']);
                }
                $recodeData[] = (new Recode())->recodeInfoFormat($item);
            }
        }
        if ($recodeData)
        {
            $order['recode_data']['des'] = implode(',', array_column($recodeData, 'name'));
            $order['recode_data']['info'] = $recodeData;
        }

        //获取订单跳转信息
        if ((int)$order['status'] === 4 && $order['is_skip'])
        {
            $order['rid'] = current($order['recode'])['id'];
            $recodeInfo = (new Recode())->getInfoById(current($order['recode'])['id']);
            $order['recode_info'] = $recodeInfo;
            $order['recode_status'] = $recodeInfo['status'];
            $targetInfo = $this->orderTypeLink($order);
        } else
        {
            $targetInfo = ['target' => 'local', 'link' => 'empty'];
        }

        if ($order['order_type'] == 5)
        {
            if (!empty($targetInfo['is_history']))
            {
                $link = 'acg_map_history';
            } else
            {
                $link = 'acg_map';
            }
            $live_id = $order['extend']['live_info']['live_id'] ?? 0;
            $config = array_column(config('map.city_score'), null, 'gid');
            $goodsGidConfig = config('goods');
            $linesGoodsKey = $goodsGidConfig['acg_line_id'];
            $rid = current($rids);
            foreach ($order['goods_data'] as $key => $good)
            {
                $order['goods_data'][$key]['target'] = 'local';
                if (isset($config[$good['id']]))//城市排行
                {
                    $typeTmp = $config[$good['id']]['type'];
                    $order['goods_data'][$key]['link'] = $link . "?rid={$rid}&live_id={$live_id}&need_auth=1&tab_index1=0&tab_index2={$typeTmp}&order_id={$order['order_id']}";
                } elseif ($good['id'] == 104)//城市排行打包
                {
                    $order['goods_data'][$key]['link'] = $link . "?rid={$rid}&live_id={$live_id}&need_auth=1&tab_index1=0&tab_index2=1&order_id={$order['order_id']}";
                } elseif (in_array($good['id'], array_merge($linesGoodsKey, [103]), false))//命格线
                {
                    $order['goods_data'][$key]['link'] = $link . "?rid={$rid}&live_id={$live_id}&need_auth=1&tab_index1=1&order_id={$order['order_id']}";
                } elseif ($good['id'] == 18)//命运之城
                {
                    $order['goods_data'][$key]['link'] = $link . "?rid={$rid}&live_id={$live_id}&need_auth=1&tab_index1=2&order_id={$order['order_id']}";
                } else
                {
                    $order['goods_data'][$key]['link'] = $targetInfo['link'];
                }
            }
        } else
        {
            $order['target'] = $targetInfo['target'];
            $order['link'] = $targetInfo['link'];
            array_walk($order['goods_data'], static function (&$v, $k, $p) use ($order)
            {
                if ($order['order_type'] == 7)
                {
                    $p['link'] = preg_replace('/gid=[0-9]*&rid/', "gid={$v['id']}&rid", $p['link']);
                }
                $v = array_merge($v, $p);
            }, ['target' => $order['target'], 'link' => $order['link'], 'rname' => '']);
        }
    }

    /**
     * 视频详情
     * @param $order
     * @throws Exception
     */
    public function VideoRead2(&$order)
    {
        //获取商品信息
        $order['goods'] = (new Goods())->batchGetInfoByIds($order['gid']);
        $order['video'] = (new ZhunleCourse())->batchGetInfoByGIds($order['gid'], ['id', 'title']);
        //重组订单拓展信息
        $this->orderGoodsActive($order);

        //获取订单跳转信息
        $targetInfo = $this->orderTypeLink($order);
        $order['target'] = $targetInfo['target'];
        $order['link'] = $targetInfo['link'];
        array_walk($order['goods_data'], static function (&$v, $k, $p)
        {
            $v = array_merge($v, $p);
        }, ['target' => $order['target'], 'link' => $order['link'], 'rname' => '']);
    }

    /**
     * vip详情
     * @param $order
     * @throws Exception
     */
    public function VipRead2(&$order)
    {
        //获取商品信息
        $order['goods'] = (new Goods())->batchGetInfoByIds($order['gid']);
        //重组订单拓展信息
        $this->orderGoodsActive($order);

        //获取订单跳转信息
        $targetInfo = $this->orderTypeLink($order);
        $order['target'] = $targetInfo['target'];
        $order['link'] = $targetInfo['link'];
        array_walk($order['goods_data'], static function (&$v, $k, $p)
        {
            $v = array_merge($v, $p);
        }, ['target' => $order['target'], 'link' => $order['link'], 'rname' => '']);
    }

    /**
     * 合盘报告详情
     * @param $order
     * @throws Exception
     */
    public function SynastryReport2(&$order)
    {
        $extend = $order['extend'] ? json_decode($order['extend'], true) : [];
        if (isset($extend['synastry_report']))
        {
            $order['synastry_report'] = $extend['synastry_report'];
        } else
        {
            $order['synastry_report'] = [
                'rid1' => 0,
                'rid2' => 0,
                'sid' => 0,
                'relation_id' => 0,
            ];
        }
        //获取商品信息
        $order['goods'] = (new Goods())->batchGetInfoByIds($order['gid']);
        //重组订单拓展信息
        $this->orderGoodsActive($order);

        $reportInfo = (new ZlSynastryReport())->getOrderRecodeBackRecode($order['order_id']);
        if ($reportInfo)
        {
            //获取合盘报告备份档案信息
            $recodeInfo = array_values(json_decode(current($reportInfo), true));

            foreach ($recodeInfo as $key => $item)
            {
                $recodeStatus = (new Recode())->getInfoById($item['id'], ['status']);
                $recodeInfo[$key]['status'] = $recodeStatus['status'];
            }
            $order['recode'] = $recodeInfo;
        } else
        {
            $order['recode'] = (new Recode())->batchGetInfoByIds([$order['synastry_report']['rid1'], $order['synastry_report']['rid2']]);
        }
        $order['recode_data'] = [
            'des' => '开通档案',
            'info' => [],
        ];
        foreach ($order['recode'] as $item)
        {
            if (!$item['status'])
            {
                Util::orderBtnReset($order['order_btn']);
            }
            $order['recode_data']['info'][] = (new Recode())->recodeInfoFormat($item);
        }

        //获取订单跳转信息
        $targetInfo = $this->orderTypeLink($order);
        $order['target'] = $targetInfo['target'];
        $order['link'] = $targetInfo['link'];
        array_walk($order['goods_data'], static function (&$v, $k, $p)
        {
            $v = array_merge($v, $p);
        }, ['target' => $order['target'], 'link' => $order['link'], 'rname' => current($order['recode'])['name']]);
    }

    /**
     * 获取解答详情
     * @param $order
     * @return array
     * @throws Exception
     */
    public function getAnswerInfo(&$order)
    {
        $extend = json_decode($order['extend'], true);
        $liveAnchorInfo = $extend['live_info'];

        $liveOrderTitle = '';
        switch ($order['order_type'])
        {
            case 19:
                $liveOrderTitle = '看盘解答';
                $history = (new LiveAnswerAstroRecord())->getInfoById($order['fid']);
                $liveOrderRecode = json_decode($history['extend'], true);
                if ((int)$history['type'] === 2)
                {
                    $liveOrderDes2 = $liveOrderRecode['recode1']['name'] . '&' . $liveOrderRecode['recode2']['name'];
                } else
                {
                    $liveOrderDes2 = $liveOrderRecode['recode1']['name'];
                }
                $recodeDataTmp = [];
                foreach ($liveOrderRecode as $item)
                {
                    if ($item)
                    {
                        $recodeDataTmp[] = (new Recode())->recodeInfoFormat($item);
                    }
                }
                $order['recode_data']['des'] = implode('&', array_column($recodeDataTmp, 'name'));
                $order['recode_data']['info'] = $recodeDataTmp;
                break;
            case 20:
                $liveOrderTitle = '骰子解答';
                break;
            case 21:
                $liveOrderTitle = '塔罗解答';
                break;
        }

        $order['goods'] = (new Goods())->batchGetInfoByIds([$order['gid']]);
        //重组订单拓展信息
        $this->orderGoodsActive($order);

        //获取订单跳转信息
        if (in_array((int)$order['status'], [1, 4], true) && $order['is_skip'])
        {
            $targetInfo = $this->orderTypeLink($order);
        } else
        {
            $targetInfo = ['target' => 'local', 'link' => 'empty'];
        }
        $order['target'] = $targetInfo['target'];
        $order['link'] = $targetInfo['link'];
        array_walk($order['goods_data'], static function (&$v, $k, $p)
        {
            $v = array_merge($v, $p);
        }, ['target' => $order['target'], 'link' => $order['link'], 'rname' => $liveOrderDes2 ?? '']);

        $order['title'] = $liveOrderTitle;
        $order['des2'] = isset($liveOrderDes2) ? '看盘档案：' . $liveOrderDes2 : '';
        $order['live_anchor'] = $liveAnchorInfo;
    }

    /**
     * 获取问答详情
     * @param $order
     * @return array
     * @throws Exception
     */
    public function getQuestionInfo(&$order)
    {
        $order['goods'] = (new Goods())->batchGetInfoByIds([$order['gid']]);
        //重组订单拓展信息
        $this->orderGoodsActive($order);
        $orderTitle = '';
        $activeTitle = '';
        $questionModel = new Zlcr2UserQuestion();
        $question = $questionModel->getInfoById($order['fid'], ['question_type', 'question_extend']);
        $res = $questionModel->getQuestionType((int)$order['gid']);
        $questionGoodsType = '';
        //追问处理
        if ($res['type'] === 2)
        {
            $questionGoodsType = '(追问)';
        }
        switch ($question['question_type'])
        {
            case 1:
                $orderTitle = '问答/星盘' . $questionGoodsType;
                $activeTitle = '问答星盘' . $questionGoodsType;
                //                if (count($question['question_extend']) > 1)
                if (isset($question['question_extend']['recode1'], $question['question_extend']['recode2']))
                {
                    $orderDes2 = $question['question_extend']['recode1']['name'] . '&' . $question['question_extend']['recode2']['name'];
                } else
                {
                    $orderDes2 = $question['question_extend']['recode1']['name'];
                }
                $recodeDataTmp = [];
                foreach ($question['question_extend'] as $k => $item)
                {
                    if ($k !== 'version' && $item)
                    {
                        $recodeDataTmp[] = (new Recode())->recodeInfoFormat($item);
                    }
                }
                $order['recode_data']['des'] = implode('&', array_column($recodeDataTmp, 'name'));
                $order['recode_data']['info'] = $recodeDataTmp;
                $order['goods_data'][0]['name'] .= '/星盘' . $questionGoodsType;
                break;
            case 2:
                $orderTitle = '问答/骰子' . $questionGoodsType;
                $activeTitle = '问答骰子' . $questionGoodsType;
                $order['goods_data'][0]['name'] .= '/骰子' . $questionGoodsType;
                break;
            case 3:
                $orderTitle = '问答/塔罗' . $questionGoodsType;
                $activeTitle = '问答塔罗' . $questionGoodsType;
                $order['goods_data'][0]['name'] .= '/塔罗' . $questionGoodsType;
                break;
        }
        //蹭看处理
        if ($res['type'] === 1)
        {
            $orderTitle = '问答/蹭看';
            $activeTitle = '问答蹭看';
            $order['goods_data'][0]['name'] = '问答/蹭看';
            $order['recode_data'] = null;
        }//追问处理
        else if ($res['type'] === 2)
        {
            $order['recode_data'] = null;
        }
        $activeData = [];
        if (isset($order['active_data']))
        {
            foreach ($order['active_data'] as $item)
            {
                $tmp = explode('/', $item['name']);
                if ((int)$order['order_type'] === 22)
                {
                    $item['name'] = $activeTitle . '/' . $tmp[1];
                } else
                {
                    $item['name'] = $tmp[0] . $orderTitle . '/' . $tmp[1];
                }
                $activeData[] = $item;
            }
            $order['active_data'] = $activeData;
        }

        //获取订单跳转信息
        if ($order['is_skip'] && in_array((int)$order['status'], [1, 4], true))
        {
            $targetInfo = $this->orderTypeLink($order);
        } else
        {
            $targetInfo = ['target' => 'local', 'link' => 'empty'];
        }
        $order['target'] = $targetInfo['target'];
        $order['link'] = $targetInfo['link'];
        array_walk($order['goods_data'], static function (&$v, $k, $p)
        {
            $v = array_merge($v, $p);
        }, ['target' => $order['target'], 'link' => $order['link'], 'rname' => $orderDes2 ?? '']);

        if (isset($order['extend']['goods_info']))
        {
            $order['goods_data'][0]['price'] = current($order['extend']['goods_info'])['price'];
        }
        $order['title'] = $orderTitle;
        $order['des2'] = isset($orderDes2) ? '看盘档案：' . $orderDes2 : '';
    }

    /**
     * 获取适合你的TA详情
     * @param $order
     * @throws Exception
     */
    public function getRelationFitInfo(&$order)
    {
        //获取商品信息
        $maps_goods = current((new OrdersGoods())->batchGetInfo([$order['id']])) ?: [];
        $gids = [];
        $rid = 0;
        foreach ($maps_goods as $order_good)
        {
            $og = json_decode($order_good, true);
            $gids[] = $og['gid'];
            $rid = $og['rid'];
        }
        $order['goods'] = (new Goods())->batchGetInfoByIds($gids);

        $recodeData = (new Zl1RelationAnalysisFitYou())->getOrderRecodeBackRecode($order['order_id']);
        if ($recodeData)
        {
            $order['recode'] = json_decode(current($recodeData), true);

        } else
        {
            $order['recode'] = (new Recode())->getInfoById($rid);
        }
        $order['recode_data']['des'] = $order['recode']['name'];
        $order['recode_data']['info'][] = (new Recode())->recodeInfoFormat($order['recode']);


        //重组订单拓展信息
        $this->orderGoodsActive($order);
        //获取订单跳转信息
        if ((int)$order['status'] === 4 && $order['is_skip'])
        {
            $targetInfo = $this->orderTypeLink($order);
        } else
        {
            $targetInfo = ['target' => 'local', 'link' => 'empty'];
        }
        array_walk($order['goods_data'], static function (&$v, $k, $p)
        {
            $v = array_merge($v, $p);
        }, ['target' => $targetInfo['target'], 'link' => $targetInfo['link'], 'rname' => '']);
    }

    /**
     * 获取你的理想型详情
     * @param $order
     * @throws Exception
     */
    public function getRelationIdeaInfo(&$order)
    {
        $order['goods'] = (new Goods())->batchGetInfoByIds([$order['gid']]);
        //重组订单拓展信息
        $this->orderGoodsActive($order);
        //获取订单跳转信息
        if ((int)$order['status'] === 4 && $order['is_skip'])
        {
            $targetInfo = $this->orderTypeLink($order);
        } else
        {
            $targetInfo = ['target' => 'local', 'link' => 'empty'];
        }
        array_walk($order['goods_data'], static function (&$v, $k, $p)
        {
            $v = array_merge($v, $p);
        }, ['target' => $targetInfo['target'], 'link' => $targetInfo['link'], 'rname' => '']);
    }

    /**
     * 获取怎么追求TA和鉴渣神器详情
     * @param $order
     * @throws Exception
     */
    public function getRelationFollowInfo(&$order)
    {
        //获取商品信息
        $maps_goods = current((new OrdersGoods())->batchGetInfo([$order['id']])) ?: [];
        $gids = [];
        $rids = [];
        foreach ($maps_goods as $order_good)
        {
            $og = json_decode($order_good, true);
            $gids[] = $og['gid'];
            $rids[] = $og['rid'];
        }
        $order['goods'] = (new Goods())->batchGetInfoByIds($gids);
        $recodeData = (new Zl1RelationAnalysisReport())->getOrderRecodeBackRecode($order['order_id']);
        if ($recodeData)
        {
            $tmpRecode = array_values(json_decode(current($recodeData), true));
            if (!$tmpRecode[1])
            {
                $order['recode'][] = $tmpRecode[0];
            } else
            {
                $order['recode'] = $tmpRecode;
            }
        } else
        {
            if ((int)$order['order_type'] === 25)
            {
                $extend = json_decode($order['extend'], true);
                $rids = array_values($extend['recode_ids']);
            }
            $order['recode'] = array_values((new Recode())->batchGetInfoByIds($rids));
        }
        $order['recode_data']['des'] = count($order['recode']) > 1 ? '2份档案' : current($order['recode'])['name'];
        foreach ($order['recode'] as $item)
        {
            $order['recode_data']['info'][] = (new Recode())->recodeInfoFormat($item);
        }
        //重组订单拓展信息
        $this->orderGoodsActive($order);
        //获取订单跳转信息
        if ((int)$order['status'] === 4 && $order['is_skip'])
        {
            $targetInfo = $this->orderTypeLink($order);
        } else
        {
            $targetInfo = ['target' => 'local', 'link' => 'empty'];
        }
        array_walk($order['goods_data'], static function (&$v, $k, $p)
        {
            $v = array_merge($v, $p);
        }, ['target' => $targetInfo['target'], 'link' => $targetInfo['link'], 'rname' => '']);
    }

    /**
     * 年运拓展详情
     * @param $order
     * @return void
     * @throws ApiException
     */
    public function getYearLife(&$order)
    {
        //获取商品信息
        $maps_goods = current((new OrdersGoods())->batchGetInfo([$order['id']])) ?: [];
        $gids = [];
        $rids = [];
        foreach ($maps_goods as $order_good)
        {
            $og = json_decode($order_good, true);
            $gids[] = $og['gid'];
            $rids[] = $og['rid'];
        }
        $order['goods'] = (new Goods())->batchGetInfoByIds($gids);


        //重组订单拓展信息
        $this->orderGoodsActive($order);
        $order['recode'][] = $recodeInfo = $order['extend']['recode_info'];
        $order['des2'] = '';

        //获取年运拓展数据
        $result = (new Zl3FortuneYearAnalysis())->getOrderFortuneAnalysis($order['uid'], $recodeInfo['id'], $order['order_id'], []);
        if (!$result)
        {
            $order['recode_data']['des'] = $recodeInfo['name'];
            foreach ($order['recode'] as $item)
            {
                $order['recode_data']['info'][] = (new Recode())->recodeInfoFormat($item);
            }
            $order['des2'] = isset($order['extend']['year_life']['des']) ? $order['extend']['year_life']['des'] : '';
        } else
        {
            $order['recode_data']['des'] = $result['recode_info']['name'];
            $order['recode_data']['info'][] = (new Recode())->recodeInfoFormat($result['recode_info']);
            $startTime = substr($result['stageyear'], 0, 4);
            $eneTime = substr($result['stageyear'], 4);
            $stageNum = (new Util())->n2c($result['stage_num']);
            $order['des2'] = "人生第{$stageNum}阶段（{$startTime}-{$eneTime}）";
        }

        //获取订单跳转信息
        if ((int)$order['status'] === 4 && $order['is_skip'])
        {
            $targetInfo = $this->orderTypeLink($order);
        } else
        {
            $targetInfo = ['target' => 'local', 'link' => 'empty'];
        }
        array_walk($order['goods_data'], static function (&$v, $k, $p)
        {
            $v = array_merge($v, $p);
        }, ['target' => $targetInfo['target'], 'link' => $targetInfo['link'], 'rname' => '']);
    }

    /**
     * 八字详情
     * @param $order
     * @return void
     * @throws Exception
     * @throws Exception
     */
    public function getBazi(&$order)
    {
        //获取商品信息
        $maps_goods = current((new OrdersGoods())->batchGetInfo([$order['id']])) ?: [];
        $gids = [];
        $rids = [];
        foreach ($maps_goods as $order_good)
        {
            $og = json_decode($order_good, true);
            $gids[] = $og['gid'];
            $rids[] = $og['rid'];
        }
        $order['goods'] = (new Goods())->batchGetInfoByIds($gids);
        $order['des2'] = '';

        //重组订单拓展信息
        $this->orderGoodsActive($order);

        if (Goods::isBaziJsjr(28, $order['gid']))
        {
            $result = (new Zl4HoroscopeGoodTimeTemp())->getInfoById($order['extend']['history']['id']);
            $order['goods_data'][0]['price'] = (string)$result['extend']['now_prize'];
            $tagInfo = (new Zl4GoodTimeTag())->getInfoById($result['tid'], ['name']);
            $startDate = date('Y-m-d', $result['start_date']);
            $endDate = date('Y-m-d', $result['end_date']);
            $order['des2'] = "{$tagInfo['name']}/{$startDate}至{$endDate} 共{$result['unlock_day_num']}天";

            //获取备份档案信息
            $order['recode'][] = $result['recode_info']['recode1'];
            if ($result['recode_info']['recode2'])
            {
                $order['recode'][] = $result['recode_info']['recode2'];
            }
        } else
        {
            $result = (new Zl4HoroscopeReport())->getOrderReport(current($rids), $order['order_id'], []);
            if ($result)
            {
                //获取备份档案信息
                $order['recode'][] = $result['recode_info'];
            } else
            {
                $order['recode'] = (new Recode())->batchGetInfoByIds($rids);
            }
        }
        $order['recode_data'] = [
            'des' => count($order['recode']) > 1 ? '2份档案' : current($order['recode'])['name'],
            'info' => [],
        ];
        foreach ($order['recode'] as $item)
        {
            $order['recode_data']['info'][] = (new Recode())->recodeInfoFormat($item);
        }

        if ((int)$order['status'] === 1 && (int)$order['gid'] === 106)
        {
            $yongshen = (new Zl4HoroscopeReport())->getOrderReport($rids[0], $order['order_id']);
            if (!$yongshen['status'])
            {
                $order['status_des'] = '等待信息补充';
                $order['des'] = '请选择是否进行信息补充，选择完成后开始计算';
                array_walk($order['goods_data'], static function (&$v, $k, $p)
                {
                    $v = array_merge($v, $p);
                }, ['target' => 'local', 'link' => "horoscope_yongshen_info?rid={$rids[0]}&order_id={$order['order_id']}&need_auth=1", 'rname' => '']);
            } else
            {
                array_walk($order['goods_data'], static function (&$v, $k, $p)
                {
                    $v = array_merge($v, $p);
                }, ['target' => 'local', 'link' => 'empty', 'rname' => '']);
            }
        } else
        {
            //获取订单跳转信息
            if ((int)$order['status'] === 4 && $order['is_skip'])
            {
                $targetInfo = $this->orderTypeLink($order);
            } else
            {
                $targetInfo = ['target' => 'local', 'link' => 'empty'];
            }
            array_walk($order['goods_data'], static function (&$v, $k, $p)
            {
                $v = array_merge($v, $p);
            }, ['target' => $targetInfo['target'], 'link' => $targetInfo['link'], 'rname' => '']);
        }
    }

    /**
     * 冥想详情
     * @param $order
     * @return void
     * @throws ApiException
     */
    public function getMeditation(&$order)
    {
        $extend = json_decode($order['extend'], true);
        $mid = array_keys($extend['meditation'])[0];
        $inSign = $extend['meditation'][$mid]['in_sign'];
        $order['goods'][$order['gid']] = (new Zl6Meditation())->goodsInfo($mid, $inSign);
        $order['title'] = $extend['meditation'][$mid]['title'];
        $order['des1'] = $inSign ? '开通星座：' . (new Util())->signTypeName($inSign)['name'] : '';
        $order['meditation_id'] = $mid;
        //重组订单拓展信息
        $this->orderGoodsActive($order);
        //获取订单跳转信息
        if ((int)$order['status'] === 4 && $order['is_skip'])
        {
            $targetInfo = $this->orderTypeLink($order);
        } else
        {
            $targetInfo = ['target' => 'local', 'link' => 'empty'];
        }
        array_walk($order['goods_data'], static function (&$v, $k, $p)
        {
            $v = array_merge($v, $p);
        }, ['target' => $targetInfo['target'], 'link' => $targetInfo['link'], 'rname' => '']);
    }

    /**
     * AI解答详情
     * @param $order
     * @return void
     * @throws ApiException
     */
    public function getAiAnswer(&$order)
    {
        $extend = json_decode($order['extend'], true);
        $order['goods'] = (new Goods())->batchGetInfoByIds([$order['gid']]);
        $order['title'] = 'AI解问题';
        $order['des1'] = '购买次数：' . $extend['ai_answer']['num'] . '次';
        //重组订单拓展信息
        $this->orderGoodsActive($order);
        //获取订单跳转信息
        if ((int)$order['status'] === 4 && $order['is_skip'])
        {
            $targetInfo = $this->orderTypeLink($order);
        } else
        {
            $targetInfo = ['target' => 'local', 'link' => 'empty'];
        }
        array_walk($order['goods_data'], static function (&$v, $k, $p)
        {
            $v = array_merge($v, $p);
        }, ['target' => $targetInfo['target'], 'link' => $targetInfo['link'], 'rname' => '']);
    }

    /**
     * 后天星座
     * @param $order
     * @return void
     * @throws Exception
     */
    public function getAcquiredAstro(&$order)
    {
        $order['goods'] = (new Goods())->batchGetInfoByIds([$order['gid']]);
        $order['title'] = '后天星座';
        $order['des1'] = '';
        //重组订单拓展信息
        $this->orderGoodsActive($order);
        //获取订单跳转信息
        if ((int)$order['status'] === 4 && $order['is_skip'])
        {
            $targetInfo = $this->orderTypeLink($order);
        } else
        {
            $targetInfo = ['target' => 'local', 'link' => 'empty'];
        }
        array_walk($order['goods_data'], static function (&$v, $k, $p)
        {
            $v = array_merge($v, $p);
        }, ['target' => $targetInfo['target'], 'link' => $targetInfo['link'], 'rname' => '']);
    }

    /**
     * AI配料详情
     * @return void
     * @throws Exception
     */
    public function getAiVoice(&$order)
    {
        $extend = json_decode($order['extend'], true);
        $order['goods'] = (new Goods())->batchGetInfoByIds([$order['gid']]);
        $order['title'] = 'AI疗愈';
        $order['des1'] = '购买时长：' . $extend['goods_info'][$order['gid']]['name'];
        //重组订单拓展信息
        $this->orderGoodsActive($order);
        //获取订单跳转信息
        if ((int)$order['status'] === 4 && $order['is_skip'])
        {
            $targetInfo = $this->orderTypeLink($order);
        } else
        {
            $targetInfo = ['target' => 'local', 'link' => 'empty'];
        }
        array_walk($order['goods_data'], static function (&$v, $k, $p)
        {
            $v = array_merge($v, $p);
        }, ['target' => $targetInfo['target'], 'link' => $targetInfo['link'], 'rname' => '']);
    }

    public function getNameAnalyzeRecord(&$order)
    {
        $order['gid'] = (int)$order['gid'];
        $extend = json_decode($order['extend'], true);
        if ((int)$order['gid'] === 164)
        {
            $order['title'] = '名字评分';
            $nameAnalyzeRecord = (new Zl9NameAnalyzeRecord())->getInfoById($extend['history']['id'], ['surname', 'name', 'rid']);
            $recode = (new Recode())->getInfoById($nameAnalyzeRecord['rid']);
            $order['des1'] = '开通档案：' . $recode['name'];
            $order['des2'] = '名字：' . $nameAnalyzeRecord['surname'] . $nameAnalyzeRecord['name'];
        } else
        {
            $nameAnalyzeRecord = (new Zl9NameAnalyzeCreateNameRecord())->getInfoById($extend['history']['id'], ['type', 'params']);
            if ($order['gid'] === 165)
            {
                $order['title'] = '起名/人名';
                $order['des1'] = '开通档案：' . $nameAnalyzeRecord['params']['recode_name'];
            } else
            {
                $order['title'] = '起名/公司';
                $order['des1'] = '开通档案：' . implode('、', array_column($nameAnalyzeRecord['params']['originator_data'], 'name'));
            }
            $order['des2'] = '';
        }

        $order['goods'] = (new Goods())->batchGetInfoByIds([$order['gid']]);
        //重组订单拓展信息
        $this->orderGoodsActive($order);
        //获取订单跳转信息
        if ((int)$order['status'] === 4 && $order['is_skip'])
        {
            $targetInfo = $this->orderTypeLink($order);
        } else
        {
            $targetInfo = ['target' => 'local', 'link' => 'empty'];
        }

        array_walk($order['goods_data'], static function (&$v, $k, $p)
        {
            $v = array_merge($v, $p);
        }, ['target' => $targetInfo['target'], 'link' => $targetInfo['link'], 'rname' => '']);
    }

    /**
     * 获取订单对应的拓展信息
     * @param $order
     * @throws Exception
     */
    public function orderGoodsActive(&$order)
    {
        //获取订单拓展字段
        $extend = $order['extend'] = $order['extend'] ? json_decode($order['extend'], true) : [];
        $order['coupon'] = $extend['coupon'] ?? [];//获取订单的优惠券信息
        $order['synastry_report'] = $extend['synastry_report'] ?? [];//获取订单的合盘报告信息
        $order['live_info'] = $extend['live_info'] ?? [];//获取订单的直播间主播信息
        $order['active'] = $extend['active'] ?? [];//获取订单的活动信息
        $order['new_active'] = $extend['new_active'] ?? [];//获取订单的活动信息新版
        if (isset($extend['mall']) && $extend['mall'])
        {
            $order['mall'] = $extend['mall'];
        } elseif ($extend)
        {
            $order['mall'] = $extend;
        } else
        {
            $order['mall'] = [];
        }
        $order['history'] = $extend['history'] ?? [];//获取订单相关的历史记录信息

        $appleGoods = config('apple_pay_goods');
        //商品活动信息重组
        $goodsNum = count($order['goods']);
        $order['goods_data'] = [];
        foreach ($order['goods'] as $key => $good)
        {
            $goodDes = '';
            $goodDes2 = '';
            switch ($good['type'])
            {
                case 1:
                    $goodName = '校准生辰服务';
                    break;
                case 2:
                    $goodName = '每日运势开通';
                    //判断该笔订单是否是活动期间购买的
                    if (isset($extend['expire_time']) && $extend['expire_time'])
                    {
                        $good['expire_time'] = $extend['expire_time'];
                    }
                    $start_time = date('Y-m-d', $order['fortune']['time']);
                    $end_time = date('Y-m-d', strtotime($good['expire_time'], $order['fortune']['time']) - 86400);
                    break;
                case 3:
                    $goodName = '月度运势开通';
                    //判断该笔订单是否是活动期间购买的
                    if (isset($extend['expire_time']) && $extend['expire_time'])
                    {
                        $good['expire_time'] = $extend['expire_time'];
                    }
                    $start_time = date('Y-m', $order['fortune']['time']);
                    $end_time = date('Y-m', strtotime($good['expire_time'], $order['fortune']['time']) - 86400);
                    break;
                case 4:
                    $goodName = '年度运势开通';
                    //判断该笔订单是否是活动期间购买的
                    if (isset($extend['expire_time']) && $extend['expire_time'])
                    {
                        $good['expire_time'] = $extend['expire_time'];
                    }
                    $start_time = date('Y', $order['fortune']['time']);
                    $end_time = date('Y', strtotime($good['expire_time'], $order['fortune']['time']) - 86400);
                    break;
                case 5:
                    $goodName = $good['name'];
                    if ($good['id'] == 18)
                    {
                        $goodDes = '开通命运之城';
                    } elseif ($good['id'] == 19)
                    {
                        $goodDes = '开通全内容打包解锁';
                    }
                    break;
                case 6:
                    $goodName = '教学视频解锁';
                    $goodDes = current($order['video'])['title'];
                    break;
                case 7://todo 其他商品的recode_data,goods_data,note_tips
                    $goodName = '一生报告解锁';
                    $goodDes .= $good['name'] . ',';
                    break;
                case 8:
                    $goodName = '开通会员';
                    $goods_extend = $good['extend'] ? json_decode($good['extend'], true) : [];
                    if (!isset($extend['vip_start_time']))
                    {
                        $UserVip = \app\common\cachemodel\OrdersLib::getUserVipTime($order['uid'], $order['gid']);//返回时间为时间戳
                        $extend['vip_start_time'] = $UserVip['vip_start_time'];
                        $extend['vip_end_time'] = $UserVip['vip_end_time'];
                    }

                    //获取商品描述
                    if (Util::CheckAppVersion('2.9.7') === '大' && Util::IsIos())
                    {
                        $goodDes = $goods_extend['ios_goods_des'] ?? '';
                    } else
                    {
                        $goodDes = $goods_extend['goods_des'] ?? '';
                    }
                    //获取用户当前vip有效时间
                    $start_time = isset($extend['vip_start_time']) ? date('Y-m-d', $extend['vip_start_time']) : '';
                    $end_time = isset($extend['vip_end_time']) ? date('Y-m-d', $extend['vip_end_time']) : '';
                    break;
                case 15:
                    $goodName = '定制报告';
                    $good['now_prize'] = $good['price'];
                    $good['name'] = $good['question_name'];
                    break;
                case 16:
                    $goodName = '塔罗占卜';
                    break;
                case 17:
                    $goodName = '合盘报告';
                    $relationConfig = config('synastryreport')[$order['synastry_report']['srid']]['relation_list'];
                    $relationInfo = $relationConfig[$order['synastry_report']['relation_id']] ?? '';
                    $srid = $extend['synastry_report']['srid'] ?? 1;
                    $goodDes = '当前关系: ' . $relationInfo['name'];
                    break;
                case 18:
                    $goodName = $good['name'];
                    $goodDes = $good['short_describe'] ?? '';
                    $goodImg = $good['intro_picture'] ?? '';
                    $good['now_prize'] = $good['price_original'];
                    break;
                case 19:
                case 20:
                case 21:
                    $goodsTmp = current($extend['goods_info']);
                    $goodName = $goodsTmp['name'];
                    $good['name'] = $goodsTmp['name'];
                    $good['now_prize'] = $goodsTmp['price'];
                    break;
                case 22:
                    $goodName = '问答';
                    $good['name'] = '问答';
                    break;
                case 23:
                    $goodName = '适合你的TA';
                    $goodDes .= $good['name'] . ',';
                    break;
                case 24:
                    $goodName = '你的理想型';
                    $goodDes = '单次解锁方案';
                    break;
                case 25:
                    $goodName = '怎么追求TA';
                    break;
                case 26:
                    $goodName = '鉴”渣“神器';
                    break;
                case 27:
                    if ((int)$order['gid'] === 91)
                    {
                        $goodName = '人生阶段';

                    } elseif ((int)$order['gid'] === 92)
                    {
                        $goodName = '年运筛查';

                    } else
                    {
                        $goodName = '年运拓展';
                    }
                    break;
                case 28:
                    $isHuawei = Util::IsHuawei();
                    if (Goods::isBaziJsjr(28, $order['gid']))
                    {
                        $goodName = '吉时吉日';
                    } elseif ((int)$order['gid'] === 106)
                    {
                        $goodName = $isHuawei ? '取用详解' : '用神详解';

                    } elseif ((int)$order['gid'] === 107)
                    {
                        $goodName = $isHuawei ? '格局解读' : '72格局判定';
                    }
                    break;
                case 29:
                    $goodName = $order['title'];
                    $goodDes = $order['des1'];
                    $goodImg = Goods::goodsImg(29);
                    break;
                case 30:
                case 31:
                    $goodName = $order['title'];
                    $goodDes = $order['des1'];
                    $goodImg = Goods::goodsImg(30);
                    break;
                case 32:
                    $goodName = $order['title'];
                    $goodDes = $order['des1'];
                    $goodImg = Goods::goodsImg(32);
                    break;
                case 34:
                    $goodName = $order['title'];
                    $goodDes = $order['des1'];
                    $goodImg = Goods::goodsImg(34);
                    break;
                case 35:
                    $goodName = $good['name'];
                    $goodDes = $order['des1'];
                    $goodDes2 = $order['des2'];
                    $goodImg = Goods::goodsImg(35);
                    break;
                default:
                    $goodName = '商品开通';
                    break;
            }
            if (isset($start_time, $end_time))
            {
                $order['order_data'][] = [
                    'name' => '开通日期',
                    'value' => $start_time . '至' . $end_time,
                    'is_copy' => 0,
                ];
            }

            $tmp = [
                'id' => (int)$good['id'],
                'name' => $goodName ?? '',
                'des' => trim($goodDes, ','),
                'des2' => trim($goodDes2, ','),
                'price' => sprintf('%.2f', $good['now_prize']),
                'img' => $goodImg ?? '',
                'srid' => $srid ?? 0,
                'start_time' => $start_time ?? '',
                'end_time' => $end_time ?? '',
            ];
            if ($order['trade_type'] === 9)
            {
                if (in_array($order['order_type'], [3, 4, 7], false))
                {
                    switch ($order['order_type'])
                    {
                        case 3:
                            $appleGoods = $appleGoods['fortune_month'];
                            break;
                        case 4:
                            $appleGoods = $appleGoods['fortune_year'];
                            break;
                        case 7:
                            $appleGoods = $appleGoods['natal_report'];
                            break;
                    }
                    $tmp['name'] = $appleGoods[$good['id']]['name'] ?? $tmp['name'];
                    $tmp['price'] = $appleGoods[$good['id']]['price'] ?? $tmp['price'];
                }
            }
            $order['goods_data'][] = $tmp;
            if (!empty($order['new_active'][$key]) && $order['new_active'][$key]['discount_price'])
            {
                $activeType = $order['new_active'][$key]['type'];
                $goodDiscountPrice = $order['new_active'][$key]['discount_price'] * $order['new_active'][$key]['num'];
                $activeName = $order['new_active'][$key]['name'];
            } elseif ($order['active'])
            {
                $activeType = 1;
                $goodDiscountPrice = $order['active']['discount_price'] / $goodsNum;
                $activeName = $order['active']['name'];
            }
            if (isset($goodDiscountPrice, $activeName, $activeType) && $goodDiscountPrice)
            {
                $order['active_data'][] = [
                    'type' => $activeType,
                    'name' => $good['name'] . '/' . $activeName,
                    'discount_price' => sprintf('%.2f', $goodDiscountPrice),
                    'now_price' => sprintf('%.2f', $good['now_prize'] - $goodDiscountPrice),
                ];
            }
        }
    }
}
